Loops to create multiple graphs

1 visualización (últimos 30 días)
sylvis
sylvis el 29 de Abr. de 2020
Comentada: Stephen23 el 29 de Abr. de 2020
I have 100 variables titled CH01, CH02... CH100.
I need to plot each one of them and save each plot as a separate graph and include each variable name in each corresponding graph.
I wanted to know how I could set this into a for loop?
  2 comentarios
the cyclist
the cyclist el 29 de Abr. de 2020
Please read this tutorial about why naming variables dynamically is a bad idea.
Is there any chance you can back track and make your variables elements of a 100-element cell array instead? CH{1},CH{2}, etc? Doing the rest of task is easier if you can.
Stephen23
Stephen23 el 29 de Abr. de 2020
"I have 100 variables titled CH01, CH02... CH100."
Using numbered variables is a sign that you are doing something wrong.
Forcing meta-data (e.g. pseudo-indices) into variable names is a sign that you are doing something wrong.
Accessing variable names dynamically in a loop is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know some reasons why:
Most likely you did not sit and write out all of those variable names by hand, in which case at some point in your code those variables were created... and that is the correct place to fix your code (it is much better to fix the problem at the source, than writing awful hack code later). For example, if you used load to import that data from .mat files then simply load into an output argument (which is a scalar structure) and then access its fields:
S = load(...)

Iniciar sesión para comentar.

Respuestas (1)

the cyclist
the cyclist el 29 de Abr. de 2020
The gross way, with dynamically named variables:
CH01 = [3 5];
CH02 = [7 11];
for ii = 1:2
varString = sprintf('CH%02d',ii);
figure(ii)
commandString = ['bar(',varString,')'];
eval(commandString)
title(varString)
end
The cleaner way, with cell arrays:
CH = {[3 5],[7 11]};
for ii = 1:2
figure(ii)
bar(CH{ii})
title(['CH',sprintf('%d',ii)])
end

Categorías

Más información sobre Variables en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by