Loops to create multiple graphs

1 次查看(过去 30 天)
sylvis
sylvis 2020-4-29
评论: Stephen23 2020-4-29
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 个评论
the cyclist
the cyclist 2020-4-29
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 2020-4-29
"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(...)

请先登录,再进行评论。

回答(1 个)

the cyclist
the cyclist 2020-4-29
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

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by