Looping within a structure

조회 수: 4 (최근 30일)
Sanjay Kamath Madhengal
Sanjay Kamath Madhengal 2019년 8월 9일
댓글: Sanjay Kamath Madhengal 2019년 8월 11일
Hello everyone,
Sorry if this question was already asked, but I couldnt find something that worked for me. I have the following Matlab struct
mystruct
point1 : struct
point2 : struct
.
.
.
.
pointN : struct
Basically a structure containing point coordinates,
what I wish to do is basically fetch the data of the structure in a loop. Unfortunately I wasnt able to achieve this. What I created was
for i = 1:N
varName = strcat('mystruct.point',int2str(i));
%fetch data using the varname
end
Basically this is a snippet out of a bigger codeflow which I have simplified for the sake of my question.
Regards,
Sanjay

채택된 답변

Stephen23
Stephen23 2019년 8월 9일
편집: Stephen23 2019년 8월 9일
You can easily loop over the fieldnames:
F = fieldnames(mystruct);
for k = 1:numel(F)
A = mystruct.(F{k});
... do whatever with A
end
or use numbers to generate the fieldnames:
for k = 1:N
F = sprintf('point%d',k);
A = mystruct.(F);
... do whatever with A
end
Note that your code would be simpler and more efficient if you used a non-scalar structure (or even a cell array), rather than accessing lots of fieldnames dynamically:
  댓글 수: 1
Sanjay Kamath Madhengal
Sanjay Kamath Madhengal 2019년 8월 11일
Thanks, this really worked well for me. Accepting this as the answer :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Neuropragmatist
Neuropragmatist 2019년 8월 9일
What are the values stored in point1.struct?
Is your question about accessing fields of the table generally? If so you should look here:
If you are asking how to extract all of the data into one matrix you might be able to use struct2table without needing your loop at all:
Then it's pretty easy to extract whole columns of data.
M.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by