Passing parameters to plot() and axes() functions?
Afficher commentaires plus anciens
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;
end
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];
plot(rand(10,1),PlotOpts);
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);
Réponses (1)
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{:})
See:
I wrote explicit argument names for X and Y for this reason:
4 commentaires
Noah Tang
le 1 Juil 2022
What about the situation where only a portion of my_plot 's varargin should be passed to the inner function, say, plot?
For example, I'd like that my function have similiar syntax as plot:
drawEllipse(PDMatrix, center)
drawEllipse(PDMatrix, center, LineSpec)
drawEllipse(__, LineSpec)
drawEllipse(ax, __)
How should I implement this?
Stephen23
le 1 Juil 2022
"How should I implement this?"
Identify the portions that you want to pass to PLOT(), and only pass those to PLOT(). Note that you can use indexing when creating a comma-separated list.
Noah Tang
le 1 Juil 2022
The last syntax where an axes object is passed first seems to make this more complicated for me, do I need an input argument list parser?
Stephen23
le 1 Juil 2022
If your function has one leading optional input it could be handled by a simple IF, something like this:
function h = drawEllipse(varargin)
a = varargin{1};
if isscalar(a) && ishghandle(a) && strcmpi(get(a,'type'),'axes')
input parsing for varargin(2:end)
else
input parsing for varargin(1:end)
a = gca();
end
Catégories
En savoir plus sur Annotations dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!