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

20 visualizaciones (últimos 30 días)
Gordon
Gordon el 12 de Oct. de 2022
Comentada: Gordon el 12 de Oct. de 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.

Respuesta aceptada

Chunru
Chunru el 12 de Oct. de 2022
Editada: Chunru el 12 de Oct. de 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 comentarios
Chunru
Chunru el 12 de Oct. de 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 el 12 de Oct. de 2022
That is perfect! Thank you so much.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by