Is there a way to use a for loop to loop through structure fields?
조회 수: 58 (최근 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!