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

26 views (last 30 days)
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.

Accepted Answer

Chunru
Chunru on 12 Oct 2022
Edited: Chunru on 12 Oct 2022
%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 Comments
Chunru
Chunru on 12 Oct 2022
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!