Loops to create multiple graphs

조회 수: 19 (최근 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에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by