当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I tell Matlab to run if one of the inputs are missing?

问题描述:

This question already has an answer here:

  • Overloading functions

    2 answers

网友答案:

You have many possibilities. You can use varargin, it will pass a cell array with all arguments to your function:

function f1(varargin)
switch numel(varargin)
    case 1
        disp(varargin{1})
    case 2
        disp(varargin{1})
        disp(varargin{2})
end
end

You could also check the number of input arguments using nargin and not use the second input argument if it not exists.

function f2(x,y)
switch nargin
    case 1
        disp(x)
    case 2
        disp(x)
        disp(y)
end
end

A third possibility is to check if y exists. It will not exist if you don't pass an argument:

function f3(x,y)
if not(exist('y','var'))
        disp(x)
else
        disp(x)
        disp(y)
end
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: