Is there a way to use a for loop to loop through structure fields?

13 views (last 30 days)
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!

Answers (3)

the cyclist
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
ans = 1×4
2 3 5 7
ans = 1×4
3 5 7 11
ans = 1×4
5 7 11 13
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
ans = 1×4
2 3 5 7
ans = 1×4
3 5 7 11
ans = 1×4
5 7 11 13

Voss
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
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 = struct with fields:
field1: 'A data here'
mystruct.field2 = B
mystruct = struct with fields:
field1: 'A data here' field2: 'B data here'
mystruct.field3 = C
mystruct = struct with fields:
field1: 'A data here' field2: 'B data here' field3: 'C data here'
fieldvec = {'field1', 'field2', 'field3'}
fieldvec = 1×3 cell array
{'field1'} {'field2'} {'field3'}
for i = 1:length(fieldvec)
plottingfunction(mystruct.(fieldvec{i}));
end
data = 'A data here'
data = 'B data here'
data = 'C data here'
function plottingfunction(data)
data
end

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!