How to use string as plot arguments

8 vues (au cours des 30 derniers jours)
Niklas Kurz
Niklas Kurz le 18 Nov 2022
Modifié(e) : Niklas Kurz le 19 Nov 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.

Réponse acceptée

Stephen23
Stephen23 le 18 Nov 2022
Modifié(e) : Stephen23 le 18 Nov 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 commentaires
Steven Lord
Steven Lord le 18 Nov 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 le 19 Nov 2022
Modifié(e) : Niklas Kurz le 19 Nov 2022
Yea, it appeared to me like an awkward kind of coding as well. Thank you for guiding me the pretty way ;)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by