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

25 Ansichten (letzte 30 Tage)
Gordon
Gordon am 12 Okt. 2022
Kommentiert: Gordon am 12 Okt. 2022
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.

Akzeptierte Antwort

Chunru
Chunru am 12 Okt. 2022
Bearbeitet: Chunru am 12 Okt. 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 Kommentare
Chunru
Chunru am 12 Okt. 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.
Gordon
Gordon am 12 Okt. 2022
That is perfect! Thank you so much.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by