How to plot different functions of different colors in the same figure in a FOR cycle

조회 수: 2 (최근 30일)
I have to plot different functions in the same figure with a FOR cycle, each with a different color by others. I've tried to build a character array but when I plot, the error is "Error using plot. Conversion to double from function_handle is not possible.". How can I solve it? Thanks
Parts of the code are:
char = {'k--' 'ro-' 'bs-' 'g^-'};
(...)
ichar = char(jj)
(...)
plot(xex, uex(xex), ichar);
  댓글 수: 1
Stephen23
Stephen23 2014년 9월 2일
Although the answers below mention this, it deserves to be stated clearly right here next to the question:
Do NOT define variables (or functions) with the same names as inbuilt functions, e.g. char in this example. It will cause all sorts of problems that you really just don't want to get into...

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2014년 8월 30일
편집: dpb 2014년 8월 30일
Almost there...
ch = {'k--' 'ro-' 'bs-' 'g^-'};
for i=1:4
plot(rand(10,1),ch{i})
if i==1, hold on, end
end
NB: the {} "curlies" to dereference the cell array instead of just the brackets.
BTW, note that didn't use "char" as a variable; char is a Matlab builtin function to build a character string array.
ADDENDUM
The pertinent section of code regarding a function handle isn't shown -- perhaps you've inadvertently aliased plot as well or the X,Y argument definitions aren't shown so the issue could be there as well...
Anyways, other than the previous aliasing of char noted, the error is in what isn't shown, not what is.
  댓글 수: 3
Francesco
Francesco 2014년 9월 2일
The correction is:
ichar = char{jj};
with the {} brackets and non the () ones.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Image Analyst
Image Analyst 2014년 8월 30일
You might find it interesting how to set the default color order - the order that gets plotted when you don't specify a color at all. See the attached demo.

Star Strider
Star Strider 2014년 8월 30일
The error you quoted is not in the code you quoted.
What are xex and uex?
Your line:
ichar = char(jj)
would return in ‘ichar’ whatever the ASCII chararacter corresponding to ‘jj’ was. It would probably correspond to a control character, with unpredictable results.
  댓글 수: 2
dpb
dpb 2014년 8월 30일
ichar = char(jj)
... would return in ‘ichar’ whatever the ASCII character corresponding to ‘jj'
Excepting he aliased the builtin char to a cell string array just ahead so that isn't the problem.
Image Analyst
Image Analyst 2014년 8월 30일
Don't you love it when they say "part of the code is..." and then don't give the part of the code that really makes a difference? For example we don't know if uex is an array or a scalar index, if "hold on" was called, if plot() is inside a loop, etc. And it makes a difference as to how we'd answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Graphics Objects에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by