I am using matlab to plot several figures and hope these figure use the same plot options. To be more specific, it looks something like this.
N = 20;
Fs = 200;
t = (0:N-1)/Fs;
x = sin(2*pi*10*t);
y = cos(2*pi*20*t);
z = x + y;
figure(1),clf;
subplot(311);
plot(t, x, 'bs-', 'MarkerFaceColor', 'b', 'LineWidth', 3);
grid on;
subplot(312);
plot(t, y, 'bs-', 'MarkerFaceColor', 'b', 'LineWidth', 3);
grid on;
subplot(313);
plot(t, z, 'bs-', 'MarkerFaceColor', 'b', 'LineWidth', 3);
grid on;
You can see the plot options are exactly the same. If I want to change the style, I have to change each of them. Is that possible assemble/group them together and pass them to the plot function?
I have tried to put them in a cell like this plotOptions = {'bs-', 'MarkerFaceColor', 'b', 'LineWidth', 3}; It doesn't work. The reason might be the plot functions would take the plotOptions as one paramter and thus failed to parse it.
Is there any one have a solution?
Kind regards.
Using a cell with the options was already a good approach. Just use {:}
, as below:
opt = {'bs-', 'MarkerFaceColor', 'b', 'LineWidth', 3};
figure(1),clf;
subplot(311);
plot(t, x, opt{:});
Then, each element of the cell is evaluated as single argument.
Solution with unique plotting function:
subplot(312);
myplot(t,y)
Save myplot
function as a separate m-file.
function myplot(t,x)
plot(t, x, 'bs-', 'MarkerFaceColor', 'b', 'LineWidth', 3);
end
The cell answer is good, another option is to set the arg value to be a variable:
faceColor = 'b';
lineWidth = 3;
figure(1),clf;
subplot(311);
plot(t, x, 'bs-', 'MarkerFaceColor', faceColor, 'LineWidth', lineWidth);
subplot(312);
plot(t, y, 'bs-', 'MarkerFaceColor', faceColor, 'LineWidth', lineWidth);
subplot(313);
plot(t, z, 'bs-', 'MarkerFaceColor', faceColor, 'LineWidth', lineWidth);
A very clean alternative approach would be to keep the plot command as simple as possible and manipulate the handles afterwards.
opts = {'Color','red','MarkerFaceColor', 'b', 'LineWidth',3};
h(1) = plot(t, x);
grid on;
subplot(312);
h(2) = plot(t, y);
grid on;
subplot(313);
h(3) = plot(t, z);
grid on;
arrayfun(@(x) set(x,opts{:}),h)
The advantage over the indeed neat approach by Nemesis is, that in case you have multiple sets of properties, like:
opts.slimRed = {'Color','red','MarkerFaceColor', 'b', 'LineWidth',1};
opts.fatBlue = {'Color','blue','MarkerFaceColor', 'b', 'LineWidth',5};
and you want to exchange them, you just need to modify one variable
arrayfun(@(x) set(x,opts.fatBlue{:}),h)
to change the appearance of a whole set of handles h
.
来源:https://stackoverflow.com/questions/29673574/is-that-possible-to-assemble-several-options-and-pass-to-the-plot-function-in-ma