MATLAB: How to create and call a simple user defined function

calccreating a functionfunctionuser defined functionuser function

I am trying to teach myself MATLAB with a book but I am having problems creating and calling user defined functions. Here is the code I used for area of a circle exactly as it is in the book:
function area= calcarea(rad)
%calcarea calculates the area of a circle
%Format of call: calcarea(radius)
%Returns the area
area=pi*rad*rad; <----------Error in this line
end
When I run it. It says Error using calcarea line 6 Not Enough Input Arguments

Best Answer

You'd have to run that from a script or the command line and supply an argument for rad. Or you can put it in a function called test.m like this
function test
% Call calcarea
theArea = calcarea(42);
function area= calcarea(rad)
%calcarea calculates the area of a circle
%Format of call: calcarea(radius)
%Returns the area
area = pi * rad * rad;
Note, in the above you can have them both in the same m-file, but you must have the "function test()" in there because otherwise you'd have a script followed by the calcarea function and you can't mix a script and a function in the same file, but you can mix two functions in the same file.
Related Question