Octave Programming Tutorial/Writing functions
< Octave Programming TutorialSyntax
In Octave, function definitions use the following syntax:
function [return value 1, return value 2, ... ] = name( [arg1, arg2, ...] ) body endfunction
Examples
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
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.