0

Maybe this is very simple question for you guys, but I'm trying to write a function in MATLAB that works when having just 2 inputs or more. I have been looking for a solution, but couldn't find exactly what I wanted. It is like this

function myfunction(x1,y1,x2,y2)

    plot(x1,y1) %// user just puts x1,y1

    %// or

    plot(x1,y1,x2,y2) %// user puts x1,y1,x2,y2

end

I want the function to work, when the user just puts x1,y1 as the input, but I also want it to work when the user puts x1,y1,x2,y2 and plot a figure.

Dan
  • 45,079
  • 17
  • 88
  • 157
Romano
  • 13
  • 1
  • 7

1 Answers1

1

You can either use varargin to accept multiple inputs or use exist to check for additional inputs. I personally prefer exist because then the input arguments can maintain useful names.

varargin Example

For your scenario, use of varargin really simplifies your function. Using varargin{:} simply passes all input arguments to plot.

function myfunction(varargin)
    plot(varargin{:})
end

exist Example

Here, exist will yield false if x2 or y2 are not supplied to the function.

function myfunction(x1, y1, x2, y2)

    if exist('x2', 'var') && exist('y2', 'var')
        plot(x1, y1, x2, y2)
    else
        plot(x1, y1)
    end
end
Suever
  • 64,497
  • 14
  • 82
  • 101