MATLAB Answers

Passing parameters to plot() and axes() functions?

72 ビュー (過去 30 日間)
Knut 2018 年 6 月 28 日
編集済み: Stephen Cobeldick 2018 年 6 月 28 日
I would like to make a function that adds functionality on top of plot. I.e. a specialized plot. Say,
function my_plot(varargin)
plot(varargin{1}, varargin{2}, 'r');
axis square;
When calling this, I might like to pass additional parameters:
my_plot(x, y, 'title', 'Hello');
Now, I could do this by explicitly capturing each passed parameter, but this quickly become tedious. I would rather pass a generic array ala the snip below, where parameter/value pairs are simply relayed directly to the plot function:
PlotOpts.LineStyle = '-.';
PlotOpts.Color = [0 1 0];
However, after some fudging around, I did not find a similar way of using axes ala:
h = axes();
AxesOpts.XLabel = 'Real';
AxesOpts.XLim = [0 1];
set(h, AxesOpts);

  0 件のコメント


回答 (1 件)

Stephen Cobeldick
Stephen Cobeldick 2018 年 6 月 28 日
編集済み: Stephen Cobeldick 2018 年 6 月 28 日
Simple option: use varargin:
function myplot(X,Y,varargin)
plot(X, Y, 'r', varargin{:})
More complex option: convert options struct to cell array:
function myplot(X,Y,S)
C = reshape(fieldnames(S),1,[]);
C(2,:) = struct2cell(S);
plot(X, Y, 'r', C{:})
I wrote explicit argument names for X and Y for this reason:

  0 件のコメント




Community Treasure Hunt

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

Start Hunting!

Translated by