- publishing free software manuals
GNU Octave Manual Version 3
by John W. Eaton, David Bateman, Søren Hauberg
Paperback (6"x9"), 568 pages
ISBN 095461206X
RRP £24.95 ($39.95)

Get a printed copy>>>

11.5 Returning From a Function

The body of a user-defined function can contain a return statement. This statement returns control to the rest of the Octave program. It looks like this:


Unlike the return statement in C, Octave's return statement cannot be used to return a value from a function. Instead, you must assign values to the list of return variables that are part of the function statement. The return statement simply makes it easier to exit a function from a deeply nested loop or conditional statement.

Here is an example of a function that checks to see if any elements of a vector are nonzero.

function retval = any_nonzero (v)
  retval = 0;
  for i = 1:length (v)
    if (v (i) != 0)
      retval = 1;
  printf ("no nonzero elements found\n");

Note that this function could not have been written using the break statement to exit the loop once a nonzero value is found without adding extra logic to avoid printing the message if the vector does contain a nonzero element.

Keyword: return
When Octave encounters the keyword return inside a function or script, it returns control to the caller immediately. At the top level, the return statement is ignored. A return statement is assumed at the end of every function definition.

ISBN 095461206XGNU Octave Manual Version 3See the print edition