Is there a way to use a for loop to loop through structure fields?
Afficher commentaires plus anciens
Hello, I am creating an aerodynmic database in which I have my data organized within a structure. I am looking for a way to use a for loop to access data fields within a structure. The fields I am interested in acessing are 4D doubles which I would like to send to a function to plot.
Essentially I was wondering if there is anyway to do something like this:
mystruct.field1 = A % A, B, C are M x N x M x N arrays
mystruct.field2 = B
mystruct.field3 = C
fieldvec = {'field1', 'field2', 'field3'}
for i = 1:length(fieldvec)
plottingfunction(mystruct.fieldvec{i})
end
As oppsed to hard coding it like this:
plottingfunction(mystruct.fieldvec1)
plottingfunction(mystruct.fieldvec2)
plottingfunction(mystruct.fieldvec3)
Thanks!
Réponses (3)
the cyclist
le 22 Août 2023
Modifié(e) : the cyclist
le 22 Août 2023
Yes, you can. (Here, I just check the size, instead of calling a function.)
mystruct.field1 = rand(2,3,5,7);
mystruct.field2 = rand(3,5,7,11);
mystruct.field3 = rand(5,7,11,13);
fieldvec = {'field1', 'field2', 'field3'};
for i = 1:length(fieldvec)
size(mystruct.(fieldvec{i})) % Note the parentheses I added
end
Here is a more compact (and I think intuitive) approach
rng default
mystruct.field1 = rand(2,3,5,7); % A, B, C are M x N x M x N arrays
mystruct.field2 = rand(3,5,7,11);
mystruct.field3 = rand(5,7,11,13);
fieldvec = ["field1", "field2", "field3"];
for f = fieldvec
size(mystruct.(f))
end
1 commentaire
Milo Bouchard
le 22 Août 2023
Voss
le 22 Août 2023
mystruct.field1 = A % A, B, C are M x N x M x N arrays
mystruct.field2 = B
mystruct.field3 = C
fieldvec = fieldnames(mystruct);
for i = 1:numel(fieldvec)
plottingfunction(mystruct.(fieldvec{i}))
end
A = 'A data here'; B = 'B data here'; C = 'C data here';
mystruct.field1 = A % A, B, C are M x N x M x N arrays
mystruct.field2 = B
mystruct.field3 = C
fieldvec = {'field1', 'field2', 'field3'}
for i = 1:length(fieldvec)
plottingfunction(mystruct.(fieldvec{i}));
end
function plottingfunction(data)
data
end
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!