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 个评论

请先登录,再进行评论。

更多回答(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