2

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});
SEU
  • 1,304
  • 4
  • 15
  • 36
  • 1
    Use a cell array. Check this out for inspiration. https://www.mathworks.com/matlabcentral/answers/8266-convert-array-to-argument-list – aosborne Feb 19 '21 at 03:34

2 Answers2

3

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).

Edric
  • 23,676
  • 2
  • 38
  • 40
  • 1
    That's not right - `plot(data)` plots multiple lines, one per column; `plot(data(:,1), data(:,2))` uses the first column of `data` as the `XData`, and the second column as the `YData`. – Edric Feb 19 '21 at 09:11
  • sorry I misunderstood something in the question. Nevermind. – Robert Seifert Feb 19 '21 at 09:22
1

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,'*');
MichaelTr7
  • 4,737
  • 2
  • 6
  • 21