function with variable amount of inputs

33 visualizaciones (últimos 30 días)
Romano Geerling
Romano Geerling el 11 de Abr. de 2016
Editada: Stephen23 el 11 de Abr. de 2016
Hello everybody,
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 input, but I also want it to work when the user puts x1,y1,x2,y2 and plot a figure.
Many thanks in advance.
Romano

Respuesta aceptada

Stephen23
Stephen23 el 11 de Abr. de 2016
Editada: Stephen23 el 11 de Abr. de 2016
Use nargin:
function myfun(x1,y1,x2,y2)
switch nargin
case 2
plot(x1,y1)
case 4
plot(x1,y1,x2,y2)
otherwise
error('This number of arguments is not supported')
end
end
Or for the general case you can use varargin: this has the disadvantage that the inputs are not named, so tab completion and the code helper tools will only show varargin instead of more useful variable names.

Más respuestas (1)

Walter Roberson
Walter Roberson el 11 de Abr. de 2016
See the documentation for varargin and nargin

Categorías

Más información sobre Creating, Deleting, and Querying Graphics Objects en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by