How to use string as plot arguments

20 次查看(过去 30 天)
I was fiddling around a lot: Having two plots, I want to spare some work and define a common string to feed into both plots arguments:
CC = winter(1)
str = '''.''MarkerSize'',12,''Color'',CC(i,:)';
plot(1:10,1:10,str)
hold on
plot(1:10,1:10,str)
It just wont't allow me to use the string as shortcut.
I tried eval and other suggestions but nothing helped to convince MATLAB to run the program.

采纳的回答

Stephen23
Stephen23 2022-11-18
编辑:Stephen23 2022-11-18
"It just wont't allow me to use the string as shortcut."
Ugh, that is a really very ugly way to code. Why not just use a much neater comma-separated list:
M = winter(1);
C = {'*', 'MarkerSize',12, 'Color',M};
plot(1:10,1:10,C{:})
hold on
plot(1:10,10:-1:1,C{:})
  3 个评论
Steven Lord
Steven Lord 2022-11-18
Two other approaches involve writing a function that encapsulates the common properties you want to set or changing the default property values before creating the plots. Since that latter approach is demonstrated on that documentation page I'll show the former.
M = winter(1);
f = @(x, y) plot(x, y, '*', 'MarkerSize',12, 'Color',M);
f(1:10,1:10)
hold on
f(1:10,10:-1:1)
With this approach if you want to give your user the option to override some of those property values or add in additional name-value pair arguments you could add in the comma-separated list approach from the answer above.
f2 = @(x, y, varargin) plot(x, y, '*', 'MarkerSize',12, 'Color',M, varargin{:});
figure
f2(1:10,1:10, 'Marker', '^', 'LineStyle', '--')
The explicit specification of the Marker as '^' in the f2 call, when passed into plot, comes later in that plot call than the specification of the marker as '*' in the linespec so it "wins".
Niklas Kurz
Niklas Kurz 2022-11-19
编辑:Niklas Kurz 2022-11-19
Yea, it appeared to me like an awkward kind of coding as well. Thank you for guiding me the pretty way ;)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Discrete Data Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by