2

I need to create a bunch of fields in a struct with names that differ only by a digit, like this:

S(1).field1 = [];
S(1).field2 = [];
S(1).field3 = [];
S(1).field4 = [];
S(1).field5 = [];

This is a short version of the list. The real one is actually long and doesn't look pretty in the script so I am wondering whether I can initiate those empty fields within a for loop. I tried:

for i = 1:5
    S(1).field{i} = [];
end

but it doesn't work.

1 Answer 1

3

Use dynamic field names: this means that S.field1 is exactly the same as S.('field1'). In action:

for k = 1:5
    S(1).(['field' num2str(k)]) = [];
end

Note that I changed the loop variable to k: num2str(i) could also return 0+1i if you're not careful.

There are also some more funky, seemingly loopless solutions, such as:

n = 5;
S = cell2struct(cell(1,5),...
                arrayfun(@(x) ['field' num2str(x)],1:n,'uniformoutput',false),...
                2);

This will create a cell {[],[],[],[],[]} for the field values, and another cell {'field1','field2',...,'field5'} for the field names, and constructs a struct from these.

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.