Asked by rihan jericho
on 30 Jan 2018

for example i want to calculate the area of a triangle. so i will use the formula 1/2(b*h). and i also want to calculate volume of a triangle and i will use 1/2(b*h*l). so when i am passing the base(b) and the height(h), i want it to give me the area, and when i am passing the base(b), height(h) and length(l) i want it to give me the volume. i want to use function for my input arguments. How can i do it?

Answer by Jan
on 31 Jan 2018

Accepted Answer

A small example code:

function r = Calculate(a, b, c)

switch nargin

case 2

disp(a)

disp(b)

r = a * b;

case 3

disp(a)

disp(b)

disp(c)

r = a * b + c;

otherwise

error('2 or 2 inputs required');

end

If you do not know how many inputs the function will get, use varargin. See

doc nargin

doc varargin

Sign in to comment.

Answer by John D'Errico
on 30 Jan 2018

Edited by John D'Errico
on 30 Jan 2018

Learn to use nargin, so you can test to see how many arguments were provided. Then you can put a branch in to do the calculation as you want.

That is, you can write a function to have three arguments, but if only two arguments were provided when you call it, MATLAB assumes it is the first two arguments. So nargin allows you to differentiate in how the function was called.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 5 Comments

## John D'Errico (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/379757-i-am-trying-to-write-a-function#comment_530366

## Jan (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/379757-i-am-trying-to-write-a-function#comment_530416

## John D'Errico (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/379757-i-am-trying-to-write-a-function#comment_530429

## John D'Errico (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/379757-i-am-trying-to-write-a-function#comment_530436

## Jan (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/379757-i-am-trying-to-write-a-function#comment_530479

Sign in to comment.