@c DO NOT EDIT!  Generated automatically by munge-texi.pl.

@c Copyright (C) 1996-2015 John W. Eaton
@c
@c This file is part of Octave.
@c
@c Octave is free software; you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by the
@c Free Software Foundation; either version 3 of the License, or (at
@c your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but WITHOUT
@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@c FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
@c for more details.
@c
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <http://www.gnu.org/licenses/>.

@node Variables
@chapter Variables
@cindex variables, user-defined
@cindex user-defined 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

@example
@group
x
x15
__foo_bar_baz__
fucnrdthsucngtagdjb
@end group
@end example

@noindent
However, names like @code{__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 @code{a} and
@code{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
@dfn{assignment operators} and @dfn{increment operators}.
@xref{Assignment Ops,,Assignment Expressions}.

There is one built-in variable with a special meaning.  The @code{ans} variable
always contains the result of the last computation, where the output wasn't
assigned to any variable.  The code @code{a = cos (pi)} will assign the value -1
to the variable @code{a}, but will not change the value of @code{ans}.  However,
the code @code{cos (pi)} will set the value of @code{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.

@cindex @code{ans}
@c ans scripts/miscellaneous/ans.m
@anchor{XREFans}
@defvr {Automatic Variable} ans
The most recently computed result that was not explicitly assigned to a
variable.

For example, after the expression

@example
3^2 + 4^2
@end example

@noindent
is evaluated, the value returned by @code{ans} is 25.
@end defvr


@c isvarname libinterp/corefcn/utils.cc
@anchor{XREFisvarname}
@deftypefn {Built-in Function} {} isvarname (@var{name})
Return true if @var{name} is a valid variable name.
@seealso{@ref{XREFiskeyword,,iskeyword}, @ref{XREFexist,,exist}, @ref{XREFwho,,who}}
@end deftypefn


@c genvarname scripts/miscellaneous/genvarname.m
@anchor{XREFgenvarname}
@deftypefn  {Function File} {@var{varname} =} genvarname (@var{str})
@deftypefnx {Function File} {@var{varname} =} genvarname (@var{str}, @var{exclusions})
Create valid unique variable name(s) from @var{str}.

If @var{str} is a cellstr, then a unique variable is created for each cell
in @var{str}.

@example
@group
genvarname (@{"foo", "foo"@})
  @result{}
     @{
       [1,1] = foo
       [1,2] = foo1
     @}
@end group
@end example

If @var{exclusions} is given, then the variable(s) will be unique to each
other and to @var{exclusions} (@var{exclusions} may be either a string or a
cellstr).

@example
@group
x = 3.141;
genvarname ("x", who ())
  @result{} x1
@end group
@end example

Note that the result is a char array or cell array of strings, not the
variables themselves.  To define a variable, @code{eval()} can be used.
The following trivial example sets @code{x} to @code{42}.

@example
@group
name = genvarname ("x");
eval ([name " = 42"]);
  @result{} x =  42
@end group
@end example

This can be useful for creating unique struct field names.

@example
@group
x = struct ();
for i = 1:3
  x.(genvarname ("a", fieldnames (x))) = i;
endfor
  @result{} x =
     @{
       a =  1
       a1 =  2
       a2 =  3
     @}
@end group
@end example

Since variable names may only contain letters, digits, and underscores,
@code{genvarname} will replace any sequence of disallowed characters with
an underscore.  Also, variables may not begin with a digit; in this case
an @samp{x} is added before the variable name.

Variable names beginning and ending with two underscores @qcode{"__"} are
valid, but they are used internally by Octave and should generally be
avoided; therefore, @code{genvarname} will not generate such names.

@code{genvarname} will also ensure that returned names do not clash with
keywords such as @qcode{"for"} and @qcode{"if"}.  A number will be
appended if necessary.  Note, however, that this does @strong{not} include
function names such as @qcode{"sin"}.  Such names should be included in
@var{exclusions} if necessary.
@seealso{@ref{XREFisvarname,,isvarname}, @ref{XREFiskeyword,,iskeyword}, @ref{XREFexist,,exist}, @ref{XREFwho,,who}, @ref{XREFtempname,,tempname}, @ref{XREFeval,,eval}}
@end deftypefn


@c namelengthmax scripts/miscellaneous/namelengthmax.m
@anchor{XREFnamelengthmax}
@deftypefn {Function File} {} namelengthmax ()
Return the @sc{matlab} compatible maximum variable name length.

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


@menu
* Global Variables::
* Persistent Variables::
* Status of Variables::
@end menu

@node Global Variables
@section Global Variables
@cindex global variables
@cindex @code{global} statement
@cindex variables, global

A variable that has been declared @dfn{global} may be accessed from
within a function body without having to pass it as a formal parameter.

A variable may be declared global using a @code{global} declaration
statement.  The following statements are all global declarations.

@example
@group
global a
global a b
global c = 2
global d = 3 e f = 5
@end group
@end example

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

@example
@group
global gvar = 1
global gvar = 2
@end group
@end example

@noindent
the value of the global variable @code{gvar} is 1, not 2.  Issuing a
@samp{clear gvar} command does not change the above behavior, but
@samp{clear all} does.

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

@example
@group
global x
function f ()
  x = 1;
endfunction
f ()
@end group
@end example

@noindent
does @emph{not} set the value of the global variable @code{x} to 1.  In
order to change the value of the global variable @code{x}, you must also
declare it to be global within the function body, like this

@example
@group
function f ()
  global x;
  x = 1;
endfunction
@end group
@end example

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

@example
@group
function f (x)
  x = 0
endfunction
@end group
@end example

@noindent
and the definition of @code{x} as a global variable at the top level,

@example
global x = 13
@end example

@noindent
the expression

@example
f (x)
@end example

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

@c isglobal libinterp/corefcn/variables.cc
@anchor{XREFisglobal}
@deftypefn {Built-in Function} {} isglobal (@var{name})
Return true if @var{name} is a globally visible variable.

For example:

@example
@group
global x
isglobal ("x")
   @result{} 1
@end group
@end example
@seealso{@ref{XREFisvarname,,isvarname}, @ref{XREFexist,,exist}}
@end deftypefn


@node Persistent Variables
@section Persistent Variables
@cindex persistent variables
@cindex @code{persistent} statement
@cindex variables, persistent
@anchor{XREFpersistent}

A variable that has been declared @dfn{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.

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

for i = 1:3
  count_calls ();
endfor

@print{} 'count_calls' has been called 1 times
@print{} 'count_calls' has been called 2 times
@print{} 'count_calls' has been called 3 times
@end group
@end example

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

@example
@group
persistent a
persistent a b
persistent c = 2
persistent d = 3 e f = 5
@end group
@end example

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

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

@example
@group
persistent pvar = 1
persistent pvar = 2
@end group
@end example

@noindent
the value of the persistent variable @code{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.

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

@noindent
This implementation behaves in exactly the same way as the previous
implementation of @code{count_calls}.

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

@example
for i = 1:2
  count_calls ();
endfor
@print{} 'count_calls' has been called 1 times
@print{} 'count_calls' has been called 2 times

clear
for i = 1:2
  count_calls ();
endfor
@print{} 'count_calls' has been called 3 times
@print{} 'count_calls' has been called 4 times

clear all
for i = 1:2
  count_calls ();
endfor
@print{} 'count_calls' has been called 1 times
@print{} 'count_calls' has been called 2 times

clear count_calls
for i = 1:2
  count_calls ();
endfor
@print{} 'count_calls' has been called 1 times
@print{} 'count_calls' has been called 2 times
@end example

@noindent
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 @code{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 @code{mlock} function
(@pxref{Function Locking}).

@node Status of Variables
@section 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 @code{who}
and its siblings @code{whos} and @code{whos_line_format} will show
different information about what is in memory, as the following shows.

@example
@group
str = "A random string";
who -variables
     @print{} *** local user variables:
     @print{}
     @print{} __nargin__  str
@end group
@end example

@c who libinterp/corefcn/variables.cc
@anchor{XREFwho}
@deftypefn  {Command} {} who
@deftypefnx {Command} {} who pattern @dots{}
@deftypefnx {Command} {} who option pattern @dots{}
@deftypefnx {Command} {C =} who ("pattern", @dots{})
List currently defined variables matching the given patterns.

Valid pattern syntax is the same as described for the @code{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.

@table @code
@item global
List variables in the global scope rather than the current scope.

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

@item -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.
@end table

If called as a function, return a cell array of defined variable names
matching the given patterns.
@seealso{@ref{XREFwhos,,whos}, @ref{XREFisglobal,,isglobal}, @ref{XREFisvarname,,isvarname}, @ref{XREFexist,,exist}, @ref{XREFregexp,,regexp}}
@end deftypefn


@c whos libinterp/corefcn/variables.cc
@anchor{XREFwhos}
@deftypefn  {Command} {} whos
@deftypefnx {Command} {} whos pattern @dots{}
@deftypefnx {Command} {} whos option pattern @dots{}
@deftypefnx {Built-in Function} {S =} whos ("pattern", @dots{})
Provide detailed information on currently defined variables matching the
given patterns.

Options and pattern syntax are the same as for the @code{who} command.

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

@table @asis
@item Attr
Attributes of the listed variable.  Possible attributes are:

@table @asis
@item blank
Variable in local scope

@item @code{a}
Automatic variable.  An automatic variable is one created by the
interpreter, for example @code{argn}.

@item @code{c}
Variable of complex type.

@item @code{f}
Formal parameter (function argument).

@item @code{g}
Variable with global scope.

@item @code{p}
Persistent variable.
@end table

@item Name
The name of the variable.

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

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

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

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

If @code{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.
@seealso{@ref{XREFwho,,who}, @ref{XREFwhos_line_format,,whos_line_format}}
@end deftypefn


@c whos_line_format libinterp/corefcn/variables.cc
@anchor{XREFwhos_line_format}
@deftypefn  {Built-in Function} {@var{val} =} whos_line_format ()
@deftypefnx {Built-in Function} {@var{old_val} =} whos_line_format (@var{new_val})
@deftypefnx {Built-in Function} {} whos_line_format (@var{new_val}, "local")
Query or set the format string used by the command @code{whos}.

A full format string is:
@c Set example in small font to prevent overfull line

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

The following command sequences are available:

@table @code
@item %a
Prints attributes of variables (g=global, p=persistent, f=formal parameter,
a=automatic variable).

@item %b
Prints number of bytes occupied by variables.

@item %c
Prints class names of variables.

@item %e
Prints elements held by variables.

@item %n
Prints variable names.

@item %s
Prints dimensions of variables.

@item %t
Prints type names of variables.
@end table

Every command may also have an alignment modifier:

@table @code
@item l
Left alignment.

@item r
Right alignment (default).

@item c
Column-aligned (only applicable to command %s).
@end table

The @code{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 @code{left-min} and @code{balance} are only available when the
column-aligned modifier is used with the command @samp{%s}.
@code{balance} specifies the column number within the field width which will
be aligned between entries.  Numbering starts from 0 which indicates the
leftmost column.  @code{left-min} specifies the minimum field width to the
left of the specified balance column.

The default format is:

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

When called from inside a function with the @qcode{"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.
@seealso{@ref{XREFwhos,,whos}}
@end deftypefn


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.

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

@c exist libinterp/corefcn/variables.cc
@anchor{XREFexist}
@deftypefn  {Built-in Function} {@var{c} =} exist (@var{name})
@deftypefnx {Built-in Function} {@var{c} =} exist (@var{name}, @var{type})
Check for the existence of @var{name} as a variable, function, file,
directory, or class.

The return code @var{c} is one of

@table @asis
@item 1
@var{name} is a variable.

@item 2
@var{name} is an absolute file name, an ordinary file in Octave's
@code{path}, or (after appending @samp{.m}) a function file in Octave's
@code{path}.

@item 3
@var{name} is a @samp{.oct} or @samp{.mex} file in Octave's @code{path}.

@item 5
@var{name} is a built-in function.

@item 7
@var{name} is a directory.

@item 103
@var{name} is a function not associated with a file (entered on the command
line).

@item 0
@var{name} does not exist.
@end table

If the optional argument @var{type} is supplied, check only for symbols of
the specified type.  Valid types are

@table @asis
@item @qcode{"var"}
Check only for variables.

@item @qcode{"builtin"}
Check only for built-in functions.

@item @qcode{"dir"}
Check only for directories.

@item @qcode{"file"}
Check only for files and directories.

@item @qcode{"class"}
Check only for classes.  (Note: This option is accepted, but not currently
implemented)
@end table

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

@code{exist} returns 2 if a regular file called @var{name} is present in
Octave's search path.  If you want information about other types of files
not on the search path you should use some combination of the functions
@code{file_in_path} and @code{stat} instead.

@seealso{@ref{XREFfile_in_loadpath,,file_in_loadpath}, @ref{XREFfile_in_path,,file_in_path}, @ref{XREFdir_in_loadpath,,dir_in_loadpath}, @ref{XREFstat,,stat}}
@end deftypefn


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.

@example
large_matrix = zeros (4000, 4000);
@end example

@noindent
Since having this variable in memory might slow down other computations,
it can be necessary to remove it manually from memory.  The @code{clear}
function allows this.

@c clear libinterp/corefcn/variables.cc
@anchor{XREFclear}
@deftypefn {Command} {} clear [options] pattern @dots{}
Delete the names matching the given patterns from the symbol table.

The pattern may contain the following special characters:

@table @code
@item ?
Match any single character.

@item *
Match zero or more characters.

@item [ @var{list} ]
Match the list of characters specified by @var{list}.  If the first
character is @code{!} or @code{^}, match all characters except those
specified by @var{list}.  For example, the pattern @samp{[a-zA-Z]} will
match all lowercase and uppercase alphabetic characters.
@end table

For example, the command

@example
clear foo b*r
@end example

@noindent
clears the name @code{foo} and all names that begin with the letter
@code{b} and end with the letter @code{r}.

If @code{clear} is called without any arguments, all user-defined
variables (local and global) are cleared from the symbol table.

If @code{clear} is called with at least one argument, only the visible
names matching the arguments are cleared.  For example, suppose you have
defined a function @code{foo}, and then hidden it by performing the
assignment @code{foo = 2}.  Executing the command @kbd{clear foo} once
will clear the variable definition and restore the definition of
@code{foo} as a function.  Executing @kbd{clear foo} a second time will
clear the function definition.

The following options are available in both long and short form

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

@item -exclusive, -x
Clear the variables that don't match the following pattern.

@item -functions, -f
Clear the function names and the built-in symbols names.

@item -global, -g
Clear global symbol names.

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

@item -classes, -c
Clears the class structure table and clears all objects.

@item -regexp, -r
The arguments are treated as regular expressions as any variables that
match will be cleared.
@end table

With the exception of @code{exclusive}, all long options can be used
without the dash as well.
@seealso{@ref{XREFwho,,who}, @ref{XREFwhos,,whos}, @ref{XREFexist,,exist}}
@end deftypefn


@c pack scripts/miscellaneous/pack.m
@anchor{XREFpack}
@deftypefn {Function File} {} pack ()
Consolidate workspace memory in @sc{matlab}.

This function is provided for compatibility, but does nothing in Octave.
@seealso{@ref{XREFclear,,clear}}
@end deftypefn


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.

@c type scripts/help/type.m
@anchor{XREFtype}
@deftypefn  {Command} {} type @var{name} @dots{}
@deftypefnx {Command} {} type -q @var{name} @dots{}
@deftypefnx {Function File} {text =} type ("@var{name}", @dots{})
Display the contents of @var{name} which may be a file, function (m-file),
variable, operator, or keyword.

@code{type} normally prepends a header line describing the category of
@var{name} such as function or variable; The @option{-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.
@end deftypefn


@c which scripts/help/which.m
@anchor{XREFwhich}
@deftypefn {Command} {} which name @dots{}
Display the type of each @var{name}.

If @var{name} is defined from a function file, the full name of the file is
also displayed.
@seealso{@ref{XREFhelp,,help}, @ref{XREFlookfor,,lookfor}}
@end deftypefn


@c what scripts/miscellaneous/what.m
@anchor{XREFwhat}
@deftypefn  {Command} {} what
@deftypefnx {Command} {} what @var{dir}
@deftypefnx {Function File} {w =} what (@var{dir})
List the Octave specific files in directory @var{dir}.

If @var{dir} is not specified then the current directory is used.

If a return argument is requested, the files found are returned in the
structure @var{w}.  The structure contains the following fields:

@table @asis
@item path
Full path to directory @var{dir}

@item m
Cell array of m-files

@item mat
Cell array of mat files

@item mex
Cell array of mex files

@item oct
Cell array of oct files

@item mdl
Cell array of mdl files

@item slx
Cell array of slx files

@item p
Cell array of p-files

@item classes
Cell array of class directories (@file{@@@var{classname}/})

@item packages
Cell array of package directories (@file{+@var{pkgname}/})
@end table

Compatibility Note: Octave does not support mdl, slx, and p files; nor does
it support package directories.  @code{what} will always return an empty
list for these categories.
@seealso{@ref{XREFwhich,,which}, @ref{XREFls,,ls}, @ref{XREFexist,,exist}}
@end deftypefn

