Clear Filters
Clear Filters

Automatically creating and editing Fields of struct with for Loop

33 views (last 30 days)
That is my current code:
%%Struct Problem
for k=1:5
struct.i(k).m=rand;
struct.i(k).n=rand;
struct.i(k).o=rand;
struct.i(k).p=rand;
struct.i(k).q=rand;
end
And I want to automate the steps in a way like this:
for k=1:5
for a=['m','n','o','p','q']
struct.i(k).a=rand;
end
end
How can I automatically create and edit fields with a for loop?

Accepted Answer

Image Analyst
Image Analyst on 17 Dec 2016
What's wrong with the first way? That's the method I'd prefer. It's much more straightforward and intuitive and easy to understand than using dynamic field names.
I really don't recommend dynamic field names, but if you insist, it is possible, though a lot more complicated than your first method:
% Initialize just one struct with 5 fields.
s = struct('m',0, 'n',0, 'o',0, 'p',0, 'q',0)
letters = {'m', 'n' 'o','p','q'}
size(s)
% Now make an array of 10 of them.
myStruct = repmat(s, 1, 10) % Whatever
size(myStruct)
for k = 1 : size(myStruct, 2)
for lIndex = 1 : length(letters)
fprintf('Assigning field %s to structure #%d\n', letters{lIndex}, k)
myStruct(k).(letters{lIndex}) = rand;
end
end
  3 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!