Is there a way to use a for loop to loop through structure fields?
86 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
the cyclist
2023-8-22
编辑:the cyclist
2023-8-22
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
2023-8-22
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
2023-8-22
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!