> How to create a structure array in matlab?

How to create a structure array in matlab?

Posted at: 2014-12-18 
How do I write a script which creates a structure array that takes a number of fields such as student, age and marks on a particular number of units.

A structure and structure array can be created a variety of different ways. For example:

S = struct;

for k = 1:5

S(k).student = 'Bob';

S(k).age = 15;

S(k).marks = [95 85 79 99 98];

end

You can even dynamically create the fields based off of an arbitrary cell array input or something like that:

function S = makeMyStruct(fieldnames, values)

% fieldnames is 1xM cell array of fieldnames

% values is NxM cell array of values, where the values in the jth column correspond to the jth fieldname

S = struct;

for r = 1:size(values, 1)

for c = 1:size(values, 2)

S(r).(fieldnames{c}) = values{c}; % The parentheses around fieldnames is the key part for dynamic fields

end

end

end

Note that in terms of memory efficiency, it is better to avoid using structure arrays and to just put the arrays in the fields if possible. For example:

S.student = {'Jimmy' ; 'Timmy' ; 'Minni'};

S.age = [15 ; 16 ; 15];

S.marks = [95 85 79 99 98 ; 94 78 80 90 92 ; 99 98 93 89 100];

just add a dot, for example:

Foo.student = 'Max';

Foo.age = 12;

also check this : http://en.wikibooks.org/wiki/MATLAB_Prog...

How do I write a script which creates a structure array that takes a number of fields such as student, age and marks on a particular number of units.