Octave Programming Tutorial/Writing functions< Octave Programming Tutorial
In Octave, function definitions use the following syntax:
function [return value 1, return value 2, ...] = name( [arg1, arg2, ...] ) body endfunction
The factorial function, which takes exactly one argument and returns one integer, is as follows.
function result = factorial( n ) if( n == 0 ) result = 1; return; else result = prod( 1:n ); endif endfunction
The following function, maxmin, returns the maximum and minimum value of two integers:
function [max,min] = maxmin( a, b ) if(a >= b ) max = a; min = b; return; else max = b; min = a; return; endif endfunction
To call a function with multiple arguments, you specify multiple variables to hold the results. For example, one could write:
[big,small] = maxmin(7,10);
After executing, the variable 'big' would store the value '10' and the variable 'small' would store '7'. If fewer than two variables are used to hold the result then fewer outputs are returned. Writing
a = maxmin(13,5)
would store 13 in the variable 'a', and would discard the value of 5.
Return to the Octave Programming tutorial index