Calling a function with 2 inputs using only a single input

29 Ansichten (letzte 30 Tage)
I have a function with inputs a and b and when i tried to call the function with one input a and use the inbuilt function isempty(b) its showing error as not enough input arguments. How can I correct this.
function out = function_name(a,b)
if ~isempty(b)
b = 0.1;
end

Akzeptierte Antwort

Adam
Adam am 3 Okt. 2018
Bearbeitet: Adam am 3 Okt. 2018
It depends how you want to handle it. Do you want 'b' to be an optional argument or do you want to force the caller to always give a value for b and support [] as a a value for it?
As the final argument to a function there is not usually much point doing the latter so I would just do e.g.
function out = myFunction( a, b )
narginchk( 1, 2 )
if exist( 'b', 'var' )
% Do some validation - optional I suppose!!
else
b = 0.1;
end
If you wanted to support 'a' being optional then you could do this by allowing [] to be a valid input and would do like above, but include
if exist( 'a', 'var' ) && ~isempty( a )

Weitere Antworten (2)

Rik
Rik am 3 Okt. 2018
You need to test for existence, not for being empty, as someone could still use an empty input.
function out=function_name(a,b)
if ~exist('b','var')
b=0.1;
elseif isempty(b)
error('b should not be empty')
end
out=a*b;
end
You can also use nargin to check the number of input arguments.

Govind Sankar Madhavan Pillai Ramachandran Nair
thank you very much for your answers, it helped me
  1 Kommentar
Rik
Rik am 4 Okt. 2018
You're welcome. The best way to thank us is to accept the answer that works best and give other working answers a vote.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by