get the value of a specific field from a structure in matlab

In MATLAB, you can access the value of a specific field in a structure using indexing. Here is an example of a structure with two fields, "name" and "age":

main.m
person.name = 'John';
person.age = 30;
39 chars
3 lines

To get the value of "name" field, you can use the dot notation:

main.m
person.name
12 chars
2 lines

This will output:

main.m
ans = 
    'John'
18 chars
3 lines

If you have the name of the field in a variable, you can use dynamic field names using the indexing notation:

main.m
field_name = 'name';
person.(field_name)
41 chars
3 lines

This will output:

main.m
ans =
    'John'
17 chars
3 lines

If you want to get multiple field values at once, you can use the square bracket notation and provide a list of field names:

main.m
person_fields = {'name', 'age'};
person_values = [person.(person_fields)];
75 chars
3 lines

This will output:

main.m
person_values =
     'John'    30
34 chars
3 lines

gistlibby LogSnag