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

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 2 Sep 2014
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...

Sign in to comment.

Accepted Answer

dpb
dpb on 30 Aug 2014
Edited: dpb on 30 Aug 2014
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 Comments

Sign in to comment.

More Answers (2)

Image Analyst
Image Analyst on 30 Aug 2014
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 on 30 Aug 2014
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 Comments
dpb
dpb on 30 Aug 2014
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 on 30 Aug 2014
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.

Sign in to comment.

Categories

Find more on Graphics Objects 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!