get field of structure in matlab

In MATLAB, to get the value of a field within a structure, you can use either dot notation or indexing.

Dot Notation

main.m
    % create a structure
    s.name = 'John';
    s.age = 25;
    s.gender = 'male';

    % access a field using dot notation
    name = s.name % returns 'John'
161 chars
8 lines

In the above code, s is a structure that contains fields name, age, and gender. To access the value of the name field, we simply use dot notation as s.name.

Indexing

main.m
    % access a field using indexing
    age = s['age'] % returns 25
68 chars
3 lines

In the above code, we access the age field of structure s using indexing. We can also use a variable that contains the field name to access the value of that field:

main.m
    % access a field using a variable
    fieldName = 'gender';
    gender = s.(fieldName) % returns 'male'
108 chars
4 lines

Here, the field name gender is stored in a variable called fieldName. We access the value of this field within structure s using the syntax s.(fieldName).

In summary, you can access the fields within a MATLAB structure using either dot notation or indexing.

gistlibby LogSnag