Function with variable number of input arguments

조회 수: 4 (최근 30일)
Sid jayadev
Sid jayadev 2014년 7월 24일
댓글: Sid jayadev 2014년 7월 24일
Hey everyone,
I created a function called matrixmultiply, and I'm trying to define it for 2, 3, and 4 input arguments. How do I do this in one single script? I've heard "varargin" and "nargin" variables could work, but I don't know how to use those.
(I've defined it separately for 4 arguments already.)
Thanks!

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 7월 24일
In your case you can just use nargin to know the number of inputs. Look at this example
function y=fcn10(a,b,c,d)
if nargin==2
y=a+b
elseif nargin==3
y=a*b*c
elseif nargin==4
y=(a+b)*(c+d)
end
  댓글 수: 1
Sid jayadev
Sid jayadev 2014년 7월 24일
ah ok great! thanks! I have a complete if..elseif..elseif...end loop for 4 arguments, so do i need to create separate if statements for 3 and 2 arguments, or can i simply continue nargin = 3 and margin in the original if statement for 4 variables?

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

추가 답변 (0개)

카테고리

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