The syntax for functions which return variables is slightly different. After the 'function' keyword, an opening square bracket begins the return variable list, which is a comma-separated list of variable names which must be defined within the function body. In the following example, two variables, 'r1' and 'r2' will be returned from the hello_world function. Note that the variables are automatically returned, there is no need for an explicit 'return' statement in the function body.

File: funcHello.m

function [r1,r2] = funcHello(s)
disp(s);
r1='Hello';
r2='World';
Calling the funcHello function without catching any output variables

>> funcHello('Hi There!');
'Hi There!
>> r1
??? Undefined function or variable 'r1'.

By default, return values from functions are not "caught", that is, they are not automatically assigned to variables in the interpreter or other functions. To catch return variables from a function, you must prefix the call to the function with a square-bracket list of comma-separated variable names; MATLAB will assign the output values to the returned variables.

The names in the interpreter do not need to match the names used in the function body, but the order of returned variables will match the order in which they are defined by the function declaration. In the example, the strings 'Hello' and 'World' are returned to the interpreter and caught in the variables s1 and s2. The user does not need to catch all the return variables. If only one return variable is caught, the square brackets can be omitted.

Calling the funcHello function catching the output variables

>> [s1,s2] = funcHello('Hi There!');
'Hi There!
>> s1
s1 = Hello
Ignoring selected output variables

We may not always need every variable, and we can ignore which outputs are bound to variables in the local scope. Say we are only interested in r2, then we can use a tilde (~) to ignore the r1 output:


>> [~,s2] = funcHello('Hi There!');
'Hi There!
>> s2
s2 = World
 
©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement