Automatically creating and editing Fields of struct with for Loop

32 次查看(过去 30 天)
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?

采纳的回答

Image Analyst
Image Analyst 2016-12-17
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by