12.07.2015 Views

GNU Octave - Local Sector 7 web page

GNU Octave - Local Sector 7 web page

GNU Octave - Local Sector 7 web page

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 13: Functions and Script Files 9113 Functions and Script FilesComplicated <strong>Octave</strong> programs can often be simplified by defining functions. Functionscan be defined directly on the command line during interactive <strong>Octave</strong> sessions, or in externalfiles, and can be called just like built-in functions.13.1 Defining FunctionsIn its simplest form, the definition of a function named name looks like this:function namebodyendfunctionA valid function name is like a valid variable name: a sequence of letters, digits and underscores,not starting with a digit. Functions share the same pool of names as variables.The function body consists of <strong>Octave</strong> statements. It is the most important part of thedefinition, because it says what the function should actually do.For example, here is a function that, when executed, will ring the bell on your terminal(assuming that it is possible to do so):function wakeupprintf ("\a");endfunctionThe printf statement (see Chapter 16 [Input and Output], <strong>page</strong> 109) simply tells <strong>Octave</strong>to print the string "\a". The special character ‘\a’ stands for the alert character (ASCII7). See Chapter 5 [Strings], <strong>page</strong> 39.Once this function is defined, you can ask <strong>Octave</strong> to evaluate it by typing the name ofthe function.Normally, you will want to pass some information to the functions you define. Thesyntax for passing parameters to a function in <strong>Octave</strong> isfunction name (arg-list)bodyendfunctionwhere arg-list is a comma-separated list of the function’s arguments. When the function iscalled, the argument names are used to hold the argument values given in the call. The listof arguments may be empty, in which case this form is equivalent to the one shown above.To print a message along with ringing the bell, you might modify the beep to look likethis:function wakeup (message)printf ("\a%s\n", message);endfunctionCalling this function using a statement like thiswakeup ("Rise and shine!");will cause <strong>Octave</strong> to ring your terminal’s bell and print the message ‘Rise and shine!’,followed by a newline character (the ‘\n’ in the first argument to the printf statement).In most cases, you will also want to get some information back from the functions youdefine. Here is the syntax for writing a function that returns a single value:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!