Octave:Writing functions

From AIMSWiki

Along with predefined functions, Octave also handle customized functions that are written by the users.


Table of contents


Considerations

It is worth mentioning that each user-defined function must be stored as a plain text, .m file which, in turn, must be saved in the same folder than the m-file that is invoked from.

On the other hand, all the variables employed in the function are local to the function, unless explicitly declared as global variables.


Syntaxis

The syntax of the Octave functions is as follows:

function [output_parameters] = file_name(input_parameters)
	statement

Where [output_parameters] is the optional, comma-separated output parameter list, file_name is the name of the file in which the function is stored, and (input_parameters) represents the input parameter list separated with commas. (input_parameters), as well as [output_parameters] may be either numbers or vectors.


Example

The following is a trivial example and has been stored in the add2Values.m file. Notice that the output parameters has been ommited. The input parameters are a and b, and the function statement, a+b, adds these two values. Since no semicolon has been included at the end of the function statement, the output will be printed to the command window.

function add2Values(a,b)
	a+b


Call a Function

User-defined functions, as well as predefined functions, are invoked from the Command window.

>add2Values(1,2)
ans =  3

A function can also be assigned to a variable or an array.

>c = add2Values(1,2)
ans =  3


Reference

  • MATLAB Functions [1] (http://web.cecs.pdx.edu/~gerry/MATLAB/programming/basics.html#funcVSscripts)


Return to the Octave index