1

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;

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've just realized this fields{m} cell array, thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.