MATLAB: I am trying to write a function.

function

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?

Best 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
Related Question