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

19 vues (au cours des 30 derniers jours)
Gordon
Gordon le 12 Oct 2022
Commenté : Gordon le 12 Oct 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.

Réponse acceptée

Chunru
Chunru le 12 Oct 2022
Modifié(e) : Chunru le 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 commentaires
Chunru
Chunru le 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.
Gordon
Gordon le 12 Oct 2022
That is perfect! Thank you so much.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by