Help with using "nargin"

조회 수: 5 (최근 30일)
RG
RG 2015년 5월 15일
편집: James Tursa 2015년 5월 15일
Hi All,
I got a function "replace(a,b,c)" where I am trying to replace input arguments with another input argument when some of them are omitted. e.g. If c is omitted, I need to replace a with 2 copies of b and if b is also omitted, a needs to be replaced with 2 zeros. I tried to use nargin, but haven't been successful, can anyone help me on what I am doing wrong?
function replace(a,b,c)
if nargin<2
a=0;
end
if nargin<3
a=b;
end
Thanks.

답변 (1개)

James Tursa
James Tursa 2015년 5월 15일
편집: James Tursa 2015년 5월 15일
Think about what happens in your code if nargin == 1. In that case, b does not exist, but you get into the nargin<3 test and try to use b. So this will fail.
Your words are not entirely clear to me, but here is a guess at what you might want:
function replace(a,b,c)
if nargin < 2
a = 0;
b = 0;
c = 0;
elseif nargin < 3
a = b;
c = 0;
end
2nd attempt at coding verbatim what you requested:
function replace(a,b,c)
if nargin < 2
a = [0 0];
elseif nargin < 3
a = [b b];
end

카테고리

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