Filter löschen
Filter löschen

How to use string as plot arguments

9 Ansichten (letzte 30 Tage)
Niklas Kurz
Niklas Kurz am 18 Nov. 2022
Bearbeitet: Niklas Kurz am 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.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by