Octave – funzioni e scripts I – 45


Capitolo nuovo, molto meno noioso (spero), qui, continuando da qui.

Funzioni e scripts
Complicated Octave programs can often be simplified by defining functions. Functions can be defined directly on the command line during interactive Octave sessions, or in external files, and can be called just like built-in functions.

Avanti, qui.

Introduzione a funzioni e script files
There are seven different things covered in this section:

  • Typing in a function at the command prompt;
  • Storing a group of commands in a file — called a script file;
  • Storing a function in a file—called a function file;
  • Subfunctions in function files;
  • Multiple functions in one script file;
  • Private functions;
  • Nested functions.

Both function files and script files end with an extension of .m, for MATLAB compatibility. If you want more than one independent functions in a file, it must be a script file (see Script Files), and to use these functions you must execute the script file before you can use the functions that are in the script file.

Avanti, qui.

Definire funzioni
In its simplest form, the definition of a function named name looks like this:

function name

A 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 Octave statements. It is the most important part of the definition, because it says what the function should actually do.
For example, here is a function that, when executed, print “ciao!” on your terminal:

function hello
  printf ("ciao!\n");


The printf statement (see Input and Output) simply tells Octave to print the string “ciao!\n“. The special character ‘\n’ stands for the newline character (ASCII 10). See Strings.
Once this function is defined, you can ask Octave to evaluate it by typing the name of the function.

Normally, you will want to pass some information to the functions you define. The syntax for passing parameters to a function in Octave is

function name (arg-list)

where arg-list is a comma-separated list of the function’s arguments. When the function is called, the argument names are used to hold the argument values given in the call. The list of arguments may be empty, in which case this form is equivalent to the one shown above.

To print a name along with the greeting, you might modify hello to look like this:

function hello_n(name)
  printf ("ciao %s!\n", name);


In most cases, you will also want to get some information back from the functions you define. Here is the syntax for writing a function that returns a single value:

function ret-var = name (arg-list)

The symbol ret-var is the name of the variable that will hold the value to be returned by the function. This variable must be defined before the end of the function body in order for the function to return a value.
Variables used in the body of a function are local to the function. Variables named in arg-list and ret-var are also local to the function. See Global Variables, for information about how to access global variables inside a function.

Notare la sintassi diversa dal solito, p.es C e Python.

For example, here is a function that computes the average of the elements of a vector:

function retval = avg (v)
  retval = sum (v) / length (v);


If we had written avg like this instead,

function retval = avg (v)
  if (isvector (v))
    retval = sum (v) / length (v);

and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this:

error: value on right hand side of assignment is undefined

because the body of the if statement was never executed, and retval was never defined. To prevent obscure errors like this, it is a good idea to always make sure that the return variables will always have values, and to produce meaningful error messages when problems are encountered. For example, avg could have been written like this:

function retval = avg (v)
  retval = 0;
  if (isvector (v))
    retval = sum (v) / length (v);
    error ("avg: expecting vector argument");

There is still one additional problem with this function. What if it is called without an argument? Without additional error checking, Octave will probably print an error message that won’t really help you track down the source of the error. To allow you to catch errors like this, Octave provides each function with an automatic variable called nargin. Each time a function is called, nargin is automatically initialized to the number of arguments that have actually been passed to the function. For example, we might rewrite the avg function like this:

function retval = avg (v)
  retval = 0;
  if (nargin != 1)
    usage ("avg (vector)");
  if (isvector (v))
    retval = sum (v) / length (v);
    error ("avg: expecting vector argument");

Although Octave does not automatically report an error if you call a function with more arguments than expected, doing so probably indicates that something is wrong. Octave also does not automatically report an error if a function is called with too few arguments, but any attempt to use a variable that has not been given a value will result in an error. To avoid such problems and to provide useful messages, we check for both possibilities and issue our own error message.

Built-in Function: nargin ()
Built-in Function: nargin (fcn)

Report the number of input arguments to a function.
Called from within a function, return the number of arguments passed to the function. At the top level, return the number of command line arguments passed to Octave.
If called with the optional argument fcn —a function name or handle— return the declared number of arguments that the function can accept.

If the last argument to fcn is varargin the returned value is negative. For example


Programming Note: nargin does not work on built-in functions.

Function File: inputname (n)
Return the name of the n-th argument to the calling function.
If the argument is not a simple variable name, return an empty string. inputname may only be used within a function body, not at the command line.


Uhmmmm… la funzione ritorna comunque un valore (l’ultimo?), verifico:


quasi-panico 😳
In pratica –se ho capito bene– inputname può essere utile solo all’interno della funzione;dubbio sulla sua utilità qui.

Built-in Function: val = silent_functions ()
Built-in Function: old_val = silent_functions (new_val)
Built-in Function: silent_functions (new_val, "local")

Query or set the internal variable that controls whether internal output from a function is suppressed.
If this option is disabled, Octave will display the results produced by evaluating expressions within a function body that are not terminated with a semicolon.
When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.


Note: ho dimenticato le parentesi dopo il nome della chiamata a funzione e questa ha funzionato normalmente (sono evidentemente opzionali); silent_functions() può servre per il debug. Chiarito così anche il punto-virgola nelle funzioni.

Nel post ci sono cose scontate, usuali e quindi probabilmente già note mischiate a altre caratteristiche di Octave (e Matlab), da acquisire perché atipiche diverse dagli altri linguaggi 😳


Posta un commento o usa questo indirizzo per il trackback.



Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.

%d blogger hanno fatto clic su Mi Piace per questo: