Automatically creating and editing Fields of struct with for Loop
40 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
1 commentaire
Réponse acceptée
Image Analyst
le 17 Déc 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!