Wrapper around plot() function to use varargin

Viewed 129

I have a several datasets which are Nx2 size. Say, it is called dat1. I want to make a wrapper function myplot() to plot it using plot() function without doing plot(dat1(:,1), dat1(:,2)) every time.

It is not a problem, but I want to be able to use all the other properties like 'LineWidth', marker etc. the same way as plot().

How do I make a wrapper myPlot() that can interpret the variable arguments similar to plot()? It should look like this:

myPlot(dat1, 'rx') should translate to plot(dat1(:,1), data1(:,2),'rx')

myPlot(data1, 'Linewidth',2) should translate to plot(dat1(:,1), data1(:,2),'Linewidth',2)

Edit: Thanks. Found an answer elsewhere

function h = myPlot(varargin)
  dat = varargin{1};
  h = plot(dat(:,1), dat(:,2), varargin{2:end});
2 Answers

How about

myPlot = @(data, varargin) plot(data(:,1), data(:,2), varargin{:})

This creates an anonymous function as per @MichaelTr7's answer, but makes it more flexible by accepting varargin, and then expanding that in the call to plot. (This is a standard technique for passing through extra arguments unchanged to another function).

Using an anonymous functions/function handles might be a way of creating a sort of wrapper function. In this case all your expected inputs can go into the @(). This can be reused as many times as you like after the initial definition.

%Function definition%
myPlot = @(Data,Line_Width,Marker_Type) plot(Data(:,1),Data(:,2),'LineWidth',Line_Width,'Marker',Marker_Type);

%Random test data%
N = 100;
dat = rand(N,2);
myPlot(dat,2,'*');
Related