Is that possible to assemble several options and pass to the plot function in matlab

那年仲夏 提交于 2019-12-01 18:47:18

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);
thewaywewalk

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!