Octave Programming Tutorial/Writing functions

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Syntax[edit | edit source]

In Octave, function definitions use the following syntax:

function [return value 1, return value 2, ... ] = name( [arg1, arg2, ...] )
    body
endfunction

Examples[edit | edit source]

Factorial Function[edit | edit source]

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

Save m-File[edit | edit source]

You can save the definition of the function in your working directory. Use the name of the function also for the filename - e.g. use the filename factorial.m for the definition of the function factorial .

Maximum and Minimum of two integer Values[edit | edit source]

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