필터 지우기
필터 지우기

Using nargin in functions

조회 수: 3 (최근 30일)
Aleksandar
Aleksandar 2011년 9월 20일
Hi all,
For simplicity say I have the following function:
function c = sum1(a, b)
if nargin < 2, b = 3; end
c = a+b;
and I want to use this function in another one:
function c = sum2(a, b)
a = 2*a;
c = sum1(a, b)
and if I try to execute for example sum2(1) it will give me an error that b is not defined. I know that it can be fixed by including the nargin line in the sum2 function instead of the sum1, but what if the sum1 function is used quite often in other functions as well? Should I include the nargin line in every parent function in which I am using sum1? Isn't it more practical to write it only once in sum1 and matlab returns an error if there isn't any nargin in sum1? Is there another way to do this?
Thanks in advance.

채택된 답변

Jan
Jan 2011년 9월 20일
Another method would be to use VARARGIN:
function c = sum1(a, b)
if nargin < 2, b = 3; end
c = a+b;
function c = sum2(a, varargin)
a = 2*a;
c = sum1(a, varargin{:})
But this is prone to errors, if you call sum2 with 3 inputs. Therefore I prefer using NARGIN if a function is called with a different number of inputs.

추가 답변 (1개)

Tigersnooze
Tigersnooze 2011년 9월 20일
Your problem is that sum2 doesn't know what to do when b is not defined--as you said, this can be solved by putting in the nargin line.
function c = sum1(a, b)
if nargin < 2
b = 3;
end
c = a + b;
function c = sum2(a, b)
if nargin < 2
b = whatever you want;
end
c = sum1(a, b);
The issue here is that your parent function (sum2) is not capable to taking fewer than 2 inputs, not that sum1 is incapable.
  댓글 수: 1
Aleksandar
Aleksandar 2011년 9월 21일
Yes, I already said that I am aware of the problem and that the nargin line in sum2 will fix it, thus making the nargin line in sum1 redundant. Thanks anyway.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by