How to create a for loop to go through data arrays?

조회 수: 24 (최근 30일)
Gordon
Gordon 2022년 10월 12일
댓글: Gordon 2022년 10월 12일
I am trying to plot a bunch of arrays that I have in a 1x1 structure, labelled data, with 178 fields. The fields are named "laser1", "laser2", ....., "laser178".
Within each field I have 2 fields/separate data arrays (of which I am only interested in the one labelled pulse). I am trying to plot all these data arrays, which if done one by one would require me to do
plot(data.laser1.pulse)
hold on
plot(data.laser2.pulse)
hold on
This can probably be quite easily solved using a for loop but I don't seem to be able to do so. I tried doing the following:
data = load('file.mat')
for x = 1:178
a = data.laser{x}.pulse;
plot(a)
hold on
end
How do I incorporta the number of the variable into the name of the array I want to plot?
PS: A better way to explain my question is asking why does this not work?
for k = 1:178
FileName=['data.laser',num2str(k), '.pulse']
plot(FileName)
hold on
end
I know this doesn't work because of the quotation marks (") but I don't know how to get rid of them.

채택된 답변

Chunru
Chunru 2022년 10월 12일
편집: Chunru 2022년 10월 12일
%data = load('file.mat');
data.laser1.pulse=randn(10,1);
data.laser2.pulse=randn(10,1);
data.laser3.pulse=randn(10,1);
data.apple.pulse=randn(10,1);
f = fields(data)
f = 4×1 cell array
{'laser1'} {'laser2'} {'laser3'} {'apple' }
f = f(contains(f, 'laser')) % select those containing laser
f = 3×1 cell array
{'laser1'} {'laser2'} {'laser3'}
for i=1:length(f)
a = data.(f{i}).pulse;
plot(a)
hold on
end
  댓글 수: 3
Chunru
Chunru 2022년 10월 12일
Basically, you find all the field names and then loop through them. If you only want to loop through some of variables, for example, laser1 and so on, you can select them by pattern match. See the update above.
Gordon
Gordon 2022년 10월 12일
That is perfect! Thank you so much.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by