MATLAB: Nargin and the if statement

ifnargin

Hi Im trying to understand how to use nargin but am having an issue. Hopefully someone can shed some light on. I copied this function from my text book
function z = sqrtfun(x,y)
if (nargin==1)
z = sqrt(x);
elseif (nargin==2)
z = sqrt(x+y);
end
Then in another script I have put together this code to call the function
clc;
clear;
close all;
x = input('x');
y = input('y');
z = sqrtfun(x,y);
fprintf('Answer z ::: %4.2f\n', z);
The issue i'm having is that if i leave y blank no value is displayed for z. If i enter a value for x and y i get an output value for z. I don't know why this happens??

Best Answer

When you leave y blank in response to an input() prompt, what you get back is an empty array, and you provide that empty array as an argument. nargin tests the number of arguments passed, not what value they are, so it knows you are passing two arguments. This leads to the calculation
sqrt(x+y)
where x is not empty but y is empty. The sum of a non-empty array and an empty array is the empty array, so the result is empty.
You should modify your code to
function z = sqrtfun(x,y)
if (nargin==1) || isempty(y)
z = sqrt(x);
else
z = sqrt(x+y);
end
Related Question