フィルターのクリア

Automatically creating and editing Fields of struct with for Loop

33 ビュー (過去 30 日間)
ga56
ga56 2016 年 12 月 17 日
コメント済み: ga56 2016 年 12 月 18 日
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 件のコメント
Image Analyst
Image Analyst 2016 年 12 月 17 日
Try this:
newStruct = myStruct(4:6);
ga56
ga56 2016 年 12 月 18 日
thank you very much :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by