Iterating structures array field's values

How to iterate/loop structures array field's values.

For 1x1 struct

student = struct();
student.name = 'jim';
student.gpa  = 1.9;

I do this :

fields = fieldnames(student)

for i=1:numel(fields)
  var =  fields(i)
end

But I don't how to iterate 1 x 2 :

student = struct();
student(1).name = 'jim';
student(1).gpa  = 1.9;

student(2).name = 'ryan';
student(2).gpa  = 1.5;

Upvotes: 1

Views: 37

Answers (1)

Suever
Suever

Reputation: 65460

You need to have either another for loop

fields = fieldnames(student);

for k = 1:numel(student)
    for m = 1:numel(fields)
        var = student(k).(fields{m});
    end
end

Alternately, you can use the fact that the dot notation will create a comma separated list and you can place them in either a cell array (for strings) or a normal array

names = {student.name};
gpas = [student.name];

I typically prefer to use the second approach most often for accessing the same field from a struct array.

Upvotes: 1

Related Questions