Variables
*********

Variables let you give names to values and refer to them later.  You have already seen variables in many of the examples.  The name of a variable must be a sequence of letters, digits and underscores, but it may not begin with a digit.  Octave does not enforce a limit on the length of variable names, but it is seldom useful to have variables with names longer than about 30 characters.  The following are all valid variable names

     x
     x15
     __foo_bar_baz__
     fucnrdthsucngtagdjb

However, names like __foo_bar_baz__ that begin and end with two underscores are understood to be reserved for internal use by Octave. You should not use them in code you write, except to access Octave's documented internal variables and built-in symbolic constants.

Case is significant in variable names.  The symbols a and A are distinct variables.

A variable name is a valid expression by itself.  It represents the variable's current value.  Variables are given new values with assignment operators and increment operators. See Assignment Expressions.

There is one automatically created variable with a special meaning.  The ans variable always contains the result of the last computation, where the output wasn't assigned to any variable.  The code a = cos (pi) will assign the value -1 to the variable a, but will not change the value of ans.  However, the code cos (pi) will set the value of ans to -1.

Variables in Octave do not have fixed types, so it is possible to first store a numeric value in a variable and then to later use the same name to hold a string value in the same program.  Variables may not be used before they have been given a value.  Doing so results in an error.

 -- Automatic Variable: ans
     The most recently computed result that was not explicitly assigned to a variable.

     For example, after the expression

          3^2 + 4^2

     is evaluated, the value returned by ans is 25.

 -- isvarname: (NAME)
     Return true if NAME is a valid variable name.

     A valid variable name is composed of letters, digits, and underscores ("_"), and the first character must not be a digit. iskeyword, exist, who

 -- VARNAME =: matlab.lang.makeValidName (STR)
 -- VARNAME =: matlab.lang.makeValidName (..., "ReplacementStyle", RS)
 -- VARNAME =: matlab.lang.makeValidName (..., "Prefix", PFX)
 -- [VARNAME, ISMODIFIED] =: matlab.lang.makeValidName (...)

     Create valid variable name VARNAME from STR.

     The input STR must be a string or a cell array of strings. The output VARNAME will be of the same type.

     A valid variable name is a sequence of letters, digits, and underscores that does not begin with a digit.

     The "ReplacementStyle" option specifies how invalid characters are handled.  Acceptable values are

     "underscore" (default)
          Replace all invalid characters with an underscore ("_").

     "delete"
          Remove any invalid character.

     "hex"
          Replace all invalid characters with their hexadecimal representation.

     Whitespace characters are always removed prior to the application of the "ReplacementStyle".  Lowercase letters following a whitespace will be changed to uppercase.

     The "Prefix" option specifies the string PFX to add as a prefix to the input if it begins with a digit.  PFX must be a valid variable name itself.  The default prefix is "x".

     The optional output ISMODIFIED is a logical array indicating whether the respective element in STR was a valid name or not.

     iskeyword, isvarname, matlab.lang.makeUniqueStrings

 -- UNIQSTR =: matlab.lang.makeUniqueStrings (STR)
 -- UNIQSTR =: matlab.lang.makeUniqueStrings (STR, EX)
 -- UNIQSTR =: matlab.lang.makeUniqueStrings (STR, EX, MAXLENGTH)
 -- [UNIQSTR, ISMODIFIED] =: matlab.lang.makeUniqueStrings (...)

     Construct a list of unique strings from a list of strings.

     The input STR must be a string or a cell array of strings. The output UNIQSTR will be of the same type.

     The algorithm makes two strings unique by appending an underscore ("_" and a numeric count to the second string.

     If EX is a string or a cell array of strings, UNIQSTR will contain elements that are unique between themselves and with respect to EX.

     If EX is an index array or a logical array for STR then it selects the subset of STR that are made unique.  Unselected elements are not modified.

     The optional input MAXLENGTH specifies the maximum length of any string in UNIQSTR.  If an input string cannot be made unique without exceeding MAXLENGTH an error is emitted.

     The optional output ISMODIFIED is a logical array indicating whether each element in STR was modified to make it unique.

     unique, matlab.lang.makeValidName

 -- namelengthmax: ()
     Return the MATLAB compatible maximum variable name length.

     Octave is capable of storing strings up to 2^31 - 1 in length. However for MATLAB compatibility all variable, function, and structure field names should be shorter than the length returned by namelengthmax.  In particular, variables stored to a MATLAB file format (*.mat) will have their names truncated to this length.

Global Variables
================

A global variable is one that may be accessed anywhere within Octave. This is in contrast to a local variable which can only be accessed outside of its current context if it is passed explicitly, such as by including it as a parameter when calling a function (fcn (LOCAL_VAR1, LOCAL_VAR2)).

A variable is declared global by using a global declaration statement. The following statements are all global declarations.

     global a
     global a b
     global c = 2
     global d = 3 e f = 5

Note that the global qualifier extends only to the next end-of-statement indicator which could be a comma (,), semicolon (;), or newline ('\n').  For example, the following code declares one global variable, A, and one local variable B to which the value 1 is assigned.

     global a, b = 1

A global variable may only be initialized once in a global statement. For example, after executing the following code

     global gvar = 1
     global gvar = 2

the value of the global variable gvar is 1, not 2.  Issuing a clear gvar command does not change the above behavior, but clear all does.

It is necessary declare a variable as global within a function body in order to access the one universal variable.  For example,

     global x
     function f ()
       x = 1;
     endfunction
     f ()

does not set the value of the global variable x to 1.  Instead, a local variable, with name x, is created and assigned the value of 1. In order to change the value of the global variable x, you must also declare it to be global within the function body, like this

     function f ()
       global x;
       x = 1;
     endfunction

Passing a global variable in a function parameter list will make a local copy and not modify the global value.  For example, given the function

     function f (x)
       x = 0
     endfunction

and the definition of x as a global variable at the top level,

     global x = 13

the expression

     f (x)

will display the value of x from inside the function as 0, but the value of x at the top level remains unchanged, because the function works with a copy of its argument.

Programming Note: While global variables occasionally are the right solution to a coding problem, modern best practice discourages their use.  Code which relies on global variables may behave unpredictably between different users and can be difficult to debug.  This is because global variables can introduce systemic changes so that localizing a bug to a particular function, or to a particular loop within a function, becomes difficult.

 -- isglobal: (NAME)
     Return true if NAME is a globally visible variable.

     For example:

          global x
          isglobal ("x")
             => 1

     isvarname, exist

Persistent Variables
====================

A variable that has been declared persistent within a function will retain its contents in memory between subsequent calls to the same function.  The difference between persistent variables and global variables is that persistent variables are local in scope to a particular function and are not visible elsewhere.

The following example uses a persistent variable to create a function that prints the number of times it has been called.

     function count_calls ()
       persistent calls = 0;
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction

     for i = 1:3
       count_calls ();
     endfor

     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times
     -| 'count_calls' has been called 3 times

As the example shows, a variable may be declared persistent using a persistent declaration statement.  The following statements are all persistent declarations.

     persistent a
     persistent a b
     persistent c = 2
     persistent d = 3 e f = 5

The behavior of persistent variables is equivalent to the behavior of static variables in C.

One restriction for persistent variables is, that neither input nor output arguments of a function can be persistent:

     function y = foo ()
       persistent y = 0;  # Not allowed!
     endfunction

     foo ()
     -| error: can't make function parameter y persistent

Like global variables, a persistent variable may only be initialized once. For example, after executing the following code

     persistent pvar = 1
     persistent pvar = 2

the value of the persistent variable pvar is 1, not 2.

If a persistent variable is declared but not initialized to a specific value, it will contain an empty matrix.  So, it is also possible to initialize a persistent variable by checking whether it is empty, as the following example illustrates.

     function count_calls ()
       persistent calls;
       if (isempty (calls))
         calls = 0;
       endif
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction

This implementation behaves in exactly the same way as the previous implementation of count_calls.

The value of a persistent variable is kept in memory until it is explicitly cleared.  Assuming that the implementation of count_calls is saved on disk, we get the following behavior.

     for i = 1:2
       count_calls ();
     endfor
     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times

     clear
     for i = 1:2
       count_calls ();
     endfor
     -| 'count_calls' has been called 3 times
     -| 'count_calls' has been called 4 times

     clear all
     for i = 1:2
       count_calls ();
     endfor
     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times

     clear count_calls
     for i = 1:2
       count_calls ();
     endfor
     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times

That is, the persistent variable is only removed from memory when the function containing the variable is removed.  Note that if the function definition is typed directly into the Octave prompt, the persistent variable will be cleared by a simple clear command as the entire function definition will be removed from memory.  If you do not want a persistent variable to be removed from memory even if the function is cleared, you should use the mlock function (see Function Locking).

Status of Variables
===================

When creating simple one-shot programs it can be very convenient to see which variables are available at the prompt.  The function who and its siblings whos and whos_line_format will show different information about what is in memory, as the following shows.

     str = "A random string";
     who
      -| Variables in the current scope:
      -|
      -| ans  str

 -- who:
 -- who: pattern ...
 -- who: option pattern ...
 -- C =: who ("pattern", ...)
     List currently defined variables matching the given patterns.

     Valid pattern syntax is the same as described for the clear command. If no patterns are supplied, all variables are listed.

     By default, only variables visible in the local scope are displayed.

     The following are valid options, but may not be combined.

     global
          List variables in the global scope rather than the current scope.

     -regexp
          The patterns are considered to be regular expressions when matching the variables to display.  The same pattern syntax accepted by the regexp function is used.

     -file
          The next argument is treated as a filename.  All variables found within the specified file are listed.  No patterns are accepted when reading variables from a file.

     If called as a function, return a cell array of defined variable names matching the given patterns. whos, isglobal, isvarname, exist, regexp

 -- whos:
 -- whos: pattern ...
 -- whos: option pattern ...
 -- S =: whos ("pattern", ...)
     Provide detailed information on currently defined variables matching the given patterns.

     Options and pattern syntax are the same as for the who command.

     Extended information about each variable is summarized in a table with the following default entries.

     Attr
          Attributes of the listed variable.  Possible attributes are:

          blank
               Variable in local scope

          c
               Variable of complex type.

          f
               Formal parameter (function argument).

          g
               Variable with global scope.

          p
               Persistent variable.

     Name
          The name of the variable.

     Size
          The logical size of the variable.  A scalar is 1x1, a vector is 1xN or Nx1, a 2-D matrix is MxN.

     Bytes
          The amount of memory currently used to store the variable.

     Class
          The class of the variable.  Examples include double, single, char, uint16, cell, and struct.

     The table can be customized to display more or less information through the function whos_line_format.

     If whos is called as a function, return a struct array of defined variable names matching the given patterns.  Fields in the structure describing each variable are: name, size, bytes, class, global, sparse, complex, nesting, persistent. who, whos_line_format

 -- VAL =: whos_line_format ()
 -- OLD_VAL =: whos_line_format (NEW_VAL)
 -- whos_line_format: (NEW_VAL, "local")
     Query or set the format string used by the command whos.

     A full format string is:

          %[modifier]<command>[:width[:left-min[:balance]]];

     The following command sequences are available:

     %a
          Prints attributes of variables (g=global, p=persistent, f=formal parameter).

     %b
          Prints number of bytes occupied by variables.

     %c
          Prints class names of variables.

     %e
          Prints elements held by variables.

     %n
          Prints variable names.

     %s
          Prints dimensions of variables.

     %t
          Prints type names of variables.

     Every command may also have an alignment modifier:

     l
          Left alignment.

     r
          Right alignment (default).

     c
          Column-aligned (only applicable to command %s).

     The width parameter is a positive integer specifying the minimum number of columns used for printing.  No maximum is needed as the field will auto-expand as required.

     The parameters left-min and balance are only available when the column-aligned modifier is used with the command %s. balance specifies the column number within the field width which will be aligned between entries.  Numbering starts from 0 which indicates the leftmost column.  left-min specifies the minimum field width to the left of the specified balance column.

     The default format is:

     "  %a:4; %ln:6; %cs:16:6:1;  %rb:12;  %lc:-1;xbackslashchar n"

     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. whos

Instead of displaying which variables are in memory, it is possible to determine if a given variable is available.  That way it is possible to alter the behavior of a program depending on the existence of a variable.  The following example illustrates this.

     if (! exist ("meaning", "var"))
       disp ("The program has no 'meaning'");
     endif

 -- C =: exist (NAME)
 -- C =: exist (NAME, TYPE)
     Check for the existence of NAME as a variable, function, file, directory, or class.

     The return code C is one of

     1
          NAME is a variable.

     2
          NAME is an absolute filename, an ordinary file in Octave's path, or (after appending .m) a function file in Octave's path.

     3
          NAME is a .oct or .mex file in Octave's path.

     5
          NAME is a built-in function.

     7
          NAME is a directory.

     8
          NAME is a class.  (Note: not currently implemented)

     103
          NAME is a function not associated with a file (entered on the command line).

     0
          NAME does not exist.

     If the optional argument TYPE is supplied, check only for symbols of the specified type.  Valid types are

     "var"
          Check only for variables.

     "builtin"
          Check only for built-in functions.

     "dir"
          Check only for directories.

     "file"
          Check only for files and directories.

     "class"
          Check only for classes.  (Note: This option is accepted, but not currently implemented)

     If no type is given, and there are multiple possible matches for name, exist will return a code according to the following priority list: variable, built-in function, oct-file, directory, file, class.

     exist returns 2 if a regular file called NAME is present in Octave's search path.  For information about other types of files not on the search path use some combination of the functions file_in_path and stat instead.

     Programming Note: If NAME is implemented by a buggy .oct/.mex file, calling EXIST may cause Octave to crash.  To maintain high performance, Octave trusts .oct/.mex files instead of sandboxing them.

     file_in_loadpath, file_in_path, dir_in_loadpath, stat

Usually Octave will manage the memory, but sometimes it can be practical to remove variables from memory manually.  This is usually needed when working with large variables that fill a substantial part of the memory. On a computer that uses the IEEE floating point format, the following program allocates a matrix that requires around 128 MB memory.

     large_matrix = zeros (4000, 4000);

Since having this variable in memory might slow down other computations, it can be necessary to remove it manually from memory.  The clear or clearvars functions do this.

 -- clear:
 -- clear: PATTERN ...
 -- clear: OPTIONS PATTERN ...
     Delete the names matching the given PATTERNs thereby freeing memory.

     The PATTERN may contain the following special characters:

     ?
          Match any single character.

     *
          Match zero or more characters.

     [ LIST ]
          Match the list of characters specified by LIST.  If the first character is ! or ^, match all characters except those specified by LIST.  For example, the pattern [a-zA-Z] will match all lowercase and uppercase alphabetic characters.

     For example, the command

          clear foo b*r

     clears the name foo and all names that begin with the letter b and end with the letter r.

     If clear is called without any arguments, all user-defined variables are cleared from the current workspace (i.e., local variables).  Any global variables present will no longer be visible in the current workspace, but they will continue to exist in the global workspace.  Functions are unaffected by this form of clear.

     The following options are available in both long and short form

     all, -all, -a
          Clear all local and global user-defined variables, and all functions from the symbol table.

     -exclusive, -x
          Clear variables that do not match the following pattern.

     functions, -functions, -f
          Clear function names from the function symbol table.  Persistent variables will be re-initialized to their default value unless the function has been locked in memory with mlock.

     global, -global, -g
          Clear global variable names.

     variables, -variables, -v
          Clear local variable names.

     classes, -classes, -c
          Clear the class structure table and all objects.

     -regexp, -r
          The PATTERN arguments are treated as regular expressions and any matches will be cleared.

     With the exception of -exclusive and -regexp, all long options can be used without the dash as well.  Note that, aside from -exclusive, only one other option may appear.  All options must appear before any patterns.

     Programming Notes: The command clear NAME only clears the variable NAME when both a variable and a (shadowed) function named NAME are currently defined.  For example, suppose you have defined a function foo, and then hidden it by performing the assignment foo = 2. Executing the command clear foo once will clear the variable definition and restore the definition of foo as a function. Executing clear foo a second time will clear the function definition.

     When a local variable name, which is linked to a global variable, is cleared only the local copy of the variable is removed.  The global copy is untouched and can be restored with global GLOBAL_VARNAME.  Conversely, clear -g GLOBAL_VARNAME will remove both the local and global variables.

     clearvars, who, whos, exist, mlock

 -- clearvars:
 -- clearvars: PATTERN ...
 -- clearvars: -regexp PATTERN ...
 -- clearvars: ... -except PATTERN ...
 -- clearvars: ... -except -regexp PATTERN ...
 -- clearvars: -global ...
     Delete the variables matching the given PATTERNs from memory.

     The PATTERN may contain the following special characters:

     ?
          Match any single character.

     *
          Match zero or more characters.

     [ LIST ]
          Match the list of characters specified by LIST.  If the first character is ! or ^, match all characters except those specified by LIST.  For example, the pattern [a-zA-Z] will match all lowercase and uppercase alphabetic characters.

     If the -regexp option is given then subsequent patterns are treated as regular expressions and any matches will be cleared.

     If the -except option is given then subsequent patterns select variables that will not be cleared.

     If the -global option is given then all patterns will be applied to global variables rather than local variables.

     When called with no arguments, clearvars deletes all local variables.

     Example Code:

     Clear all variables starting with 'x' and the specific variable "foobar"

          clearvars x* foobar

     Clear the specific variable "foobar" and use regular expressions to clear all variables starting with 'x' or 'y'.

          clearvars foobar -regexp ^x ^y

     Clear all variables except for "foobar"

          clearvars -except foobar

     Clear all variables beginning with "foo", except for those ending in "bar"

          clearvars foo* -except -regexp bar$

     clear, who, whos, exist

 -- pack: ()
     Consolidate workspace memory in MATLAB.

     This function is provided for compatibility, but does nothing in Octave. clear

Information about a function or variable such as its location in the file system can also be acquired from within Octave.  This is usually only useful during development of programs, and not within a program.

 -- type: NAME ...
 -- type: -q NAME ...
 -- text =: type ("NAME", ...)
     Display the contents of NAME which may be a file, function (m-file), variable, operator, or keyword.

     type normally prepends a header line describing the category of NAME such as function or variable; The -q option suppresses this behavior.

     If no output variable is used the contents are displayed on screen. Otherwise, a cell array of strings is returned, where each element corresponds to the contents of each requested function.

 -- which: name ...
     Display the type of each NAME.

     If NAME is defined from a function file, the full name of the file is also displayed. help, lookfor

 -- what:
 -- what: DIR
 -- w =: what (DIR)
     List the Octave specific files in directory DIR.

     If DIR is not specified then the current directory is used.

     If a return argument is requested, the files found are returned in the structure W.  The structure contains the following fields:

     path
          Full path to directory DIR

     m
          Cell array of m-files

     mat
          Cell array of mat files

     mex
          Cell array of mex files

     oct
          Cell array of oct files

     mdl
          Cell array of mdl files

     slx
          Cell array of slx files

     p
          Cell array of p-files

     classes
          Cell array of class directories (@CLASSNAME/)

     packages
          Cell array of package directories (+PKGNAME/)

     Compatibility Note: Octave does not support mdl, slx, and p files. what will always return an empty list for these categories. which, ls, exist