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?
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
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.