Is there a way to use a for loop to loop through structure fields?
13 views (last 30 days)
Show older comments
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!
0 Comments
Answers (3)
the cyclist
on 22 Aug 2023
Edited: the cyclist
on 22 Aug 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
Voss
on 22 Aug 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
Walter Roberson
on 22 Aug 2023
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
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!