2

I have a nested for loop and would like to create named fields within the first loop and then save to that field within the next loop. Something like the below code where the first iteration would create structure.first and add 'works' to that field. Thanks!

structure = [];
namelist = ['first', 'second', 'third'];
p = 5;
for i = 1:p
    structure(end+1) = struct(namelist(i), {});
    for j = 1:10
        if condition = true
            structure(j).namelist(i) = 'works';
        end
    end
end
2
  • In the if condition = true case, should that be structure(j)...? Commented Jan 25, 2016 at 1:56
  • I don't know, I'm sure this is full of flaws, I've just started using structures so was just hoping to get enough code in to make it clear what I was trying to do. Commented Jan 25, 2016 at 2:01

1 Answer 1

4

A few problems with your code. Here's a cleaned up version. Note that the best way to add a field to a structure from a string value is of the form: <<struct_name>>.(<<field_name_str>>) = <<value>>. Also, the if statement tests whether a condition holds or not, so no need to test if it is true. Finally, namelist should be stored as a cell array.

structure = [];
namelist = {'first', 'second', 'third'};
for i = 1:length(namelist)
    for j = 1:10
        if condition
            structure.(namelist{i})='works';
        end
    end
end
Sign up to request clarification or add additional context in comments.

Comments

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.