Loops to create multiple graphs

1 view (last 30 days)
sylvis
sylvis on 29 Apr 2020
Commented: Stephen23 on 29 Apr 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 Comments
the cyclist
the cyclist on 29 Apr 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 on 29 Apr 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(...)

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 29 Apr 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

Categories

Find more on Variables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!