nargin and the if statement

41 ビュー (過去 30 日間)
Nicholas Salce
Nicholas Salce 2016 年 9 月 22 日
コメント済み: Mukesh Mani 2023 年 7 月 6 日
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??

採用された回答

Walter Roberson
Walter Roberson 2016 年 9 月 22 日
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
  2 件のコメント
Sultan Al-Hammadi
Sultan Al-Hammadi 2018 年 11 月 27 日
what does nargin do?
Mukesh Mani
Mukesh Mani 2023 年 7 月 6 日
nargin tests the number of arguments passed

サインインしてコメントする。

その他の回答 (1 件)

KSSV
KSSV 2016 年 9 月 22 日
You change the function as follows:
function z = sqrtfun(x,varargin)
if (nargin==1)
z = sqrt(x);
elseif (nargin==2)
y = varargin{1} ;
z = sqrt(x+y);
end
When you enter one value i.e. x nargin = 1 then it goes to if, if you enter two values i.e x,y nargin will be 2. y will be stored in varargin and we are calling it in else statement.
  2 件のコメント
Sultan Al-Hammadi
Sultan Al-Hammadi 2018 年 11 月 27 日
what does nargin do?
and what is the functionality of "varargin{1}"?
Steven Lord
Steven Lord 2018 年 11 月 27 日
See the description and examples on the nargin function documentation page for more information about what it does and how to use it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by