How to use string as plot arguments

8 visualizaciones (últimos 30 días)
Niklas Kurz
Niklas Kurz el 18 de Nov. de 2022
Editada: Niklas Kurz el 19 de Nov. de 2022
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.

Respuesta aceptada

Stephen23
Stephen23 el 18 de Nov. de 2022
Editada: Stephen23 el 18 de Nov. de 2022
"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 comentarios
Steven Lord
Steven Lord el 18 de Nov. de 2022
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 el 19 de Nov. de 2022
Editada: Niklas Kurz el 19 de Nov. de 2022
Yea, it appeared to me like an awkward kind of coding as well. Thank you for guiding me the pretty way ;)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by