Section 8.3 Calling a Function
Let’s now take a closer look at the function definition line and how to call functions in MATLAB.
The general syntax of the function definition line is:
function [output args] = function_name(input args)
An
end
statement is permitted but optional in a functionA function can have no, one or multiple input arguments and similarly, no, one or multiple output arguments. Here are some examples of the different forms that the function definition line can therefore take:
function trajectory(velo,hght,g) % no return value, three inputs
function A = RectArea(length,width) % one return value, two inputs
function [V,A] = SphereVolArea(radius) % two return values, one input
function [mpay,tpay] = loan(amount,rate,years) % two returns, three inputs
Let’s take a look at how to call the ShpereVolArea function:
>> rad = 45.4; >> [Vol Area] = SphereVolArea(rad)
Vol = 26015.5
Area = 394568.9
The function returns to values and so both Vol and Area are assigned values as a result of calling this function.
Again, MATLAB has no pointers and so there is no need to pass output parameters as arguments to functions.
All variables are passed by value to functions; therefore any modifications within functions happen to copies of the function arguments and not to the original variables that live outside of the function.
All variables are local to the functions including input and output arguments (they are recognized only inside the function files) unless explicitly defined otherwise.
When a function file is executed a separate memory location is used for all variables that pertain to the function, i.e. one that is different than that used for script files and the workspace.
A function file can have variables with the same name as variables in the command window and workspace, and a function does NOT recognize variables defined elsewhere.