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

@c Copyright (C) 2012-2026 The Octave Project Developers
@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
@c the Free Software Foundation, either version 3 of the License, or
@c (at your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but
@c WITHOUT ANY WARRANTY; without even the implied warranty of
@c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@c GNU General Public License 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 <https://www.gnu.org/licenses/>.

@node Vectorization and Faster Code Execution
@chapter Vectorization and Faster Code Execution
@cindex vectorization
@cindex vectorize

Vectorization is a programming technique that uses vector operations
instead of element-by-element loop-based operations.  Besides frequently
producing more succinct Octave code, vectorization also allows for better
optimization in the subsequent implementation.  The optimizations may occur
either in Octave's own Fortran, C, or C++ internal implementation, or even at a
lower level depending on the compiler and external numerical libraries used to
build Octave.  The ultimate goal is to make use of your hardware's vector
instructions if possible or to perform other optimizations in software.

Vectorization is not a concept unique to Octave, but it is particularly
important because Octave is a matrix-oriented language.  Vectorized
Octave code will see a dramatic speed up (10X--100X) in most cases.

This chapter discusses vectorization and other techniques for writing faster
code.

@menu
* Basic Vectorization::        Basic techniques for code optimization
* Broadcasting::               Broadcasting operations
* Function Application::       Applying functions to arrays, cells, and structs
* Accumulation::               Accumulation functions
* Memoization::                Memoization techniques
* Miscellaneous Techniques::   Other techniques for speeding up code
* Examples::
@end menu

@node Basic Vectorization
@section Basic Vectorization

To a very good first approximation, the goal in vectorization is to
write code that avoids loops and uses whole-array operations.  As a
trivial example, consider

@example
@group
for i = 1:n
  for j = 1:m
    c(i,j) = a(i,j) + b(i,j);
  endfor
endfor
@end group
@end example

@noindent
compared to the much simpler

@example
c = a + b;
@end example

@noindent
This isn't merely easier to write; it is also internally much easier to
optimize.  Octave delegates this operation to an underlying
implementation which, among other optimizations, may use special vector
hardware instructions or could conceivably even perform the additions in
parallel.  In general, if the code is vectorized, the underlying
implementation has more freedom about the assumptions it can make
in order to achieve faster execution.

This is especially important for loops with "cheap" bodies.  Often it
suffices to vectorize just the innermost loop to get acceptable
performance.  A general rule of thumb is that the "order" of the
vectorized body should be greater or equal to the "order" of the
enclosing loop.

As a less trivial example, instead of

@example
@group
for i = 1:n-1
  a(i) = b(i+1) - b(i);
endfor
@end group
@end example

@noindent
write

@example
a = b(2:n) - b(1:n-1);
@end example

This shows an important general concept about using arrays for indexing
instead of looping over an index variable.  @xref{Index Expressions}.
Also use boolean indexing generously.  If a condition needs to be tested,
this condition can also be written as a boolean index.  For instance,
instead of

@example
@group
for i = 1:n
  if (a(i) > 5)
    a(i) -= 20
  endif
endfor
@end group
@end example

@noindent
write

@example
a(a>5) -= 20;
@end example

@noindent
which exploits the fact that @code{a > 5} produces a boolean index.

Use elementwise vector operators whenever possible to avoid looping
(operators like @code{.*} and @code{.^}).  @xref{Arithmetic Ops}.

Also exploit broadcasting in these elementwise operators both to avoid
looping and unnecessary intermediate memory allocations.
@xref{Broadcasting}.

Use built-in and library functions if possible.  Built-in and compiled
functions are very fast.  Even with an m-file library function, chances
are good that it is already optimized, or will be optimized more in a
future release.

For instance, even better than

@example
a = b(2:n) - b(1:n-1);
@end example

@noindent
is

@example
a = diff (b);
@end example

Most Octave functions are written with vector and array arguments in
mind.  If you find yourself writing a loop with a very simple operation,
chances are that such a function already exists.  The following functions
occur frequently in vectorized code:

@itemize @bullet
@item
Index manipulation

@itemize
@item
find

@item
sub2ind

@item
ind2sub

@item
sort

@item
unique

@item
lookup

@item
ifelse / merge
@end itemize

@item
Repetition

@itemize
@item
repmat

@item
repelems
@end itemize

@item
Vectorized arithmetic

@itemize
@item
sum

@item
prod

@item
cumsum

@item
cumprod

@item
sumsq

@item
diff

@item
dot

@item
cummax

@item
cummin
@end itemize

@item
Shape of higher dimensional arrays

@itemize
@item
reshape

@item
resize

@item
permute

@item
squeeze

@item
deal
@end itemize

@end itemize

@node Broadcasting
@section Broadcasting
@cindex broadcast
@cindex broadcasting
@cindex @nospell{BSX}
@cindex recycling
@cindex SIMD

@menu
* Broadcasting and Legacy Code::
@end menu

Broadcasting refers to how Octave binary operators and functions behave
when their matrix or array operands or arguments differ in size.  Since
version 3.6.0, Octave now automatically broadcasts vectors, matrices,
and arrays when using elementwise binary operators and functions.
Broadly speaking, smaller arrays are ``broadcast'' across the larger
one, until they have a compatible shape.  The rule is that corresponding
array dimensions must either

@enumerate
@item
be equal, or

@item
one of them must be 1.
@end enumerate

@noindent
In case all dimensions are equal, no broadcasting occurs and ordinary
element-by-element arithmetic takes place.  For arrays of higher
dimensions, if the number of dimensions isn't the same, then missing
trailing dimensions are treated as 1.  When one of the dimensions is 1,
the array with that singleton dimension gets copied along that dimension
until it matches the dimension of the other array.  For example, consider

@example
@group
x = [1 2 3;
     4 5 6;
     7 8 9];

y = [10 20 30];

x + y
@end group
@end example

@noindent
Without broadcasting, @code{x + y} would be an error because the dimensions
do not agree.  However, with broadcasting it is as if the following
operation were performed:

@example
@group
x = [1 2 3
     4 5 6
     7 8 9];

y = [10 20 30
     10 20 30
     10 20 30];

x + y
@xresult{}    11   22   33
      14   25   36
      17   28   39
@end group
@end example

@noindent
That is, the smaller array of size @code{[1 3]} gets copied along the
singleton dimension (the number of rows) until it is @code{[3 3]}.  No
actual copying takes place, however.  The internal implementation reuses
elements along the necessary dimension in order to achieve the desired
effect without copying in memory.

Both arrays can be broadcast across each other, for example, all
pairwise differences of the elements of a vector with itself:

@example
@group
y - y'
@xresult{}    0   10   20
    -10    0   10
    -20  -10    0
@end group
@end example

@noindent
Here the vectors of size @code{[1 3]} and @code{[3 1]} both get
broadcast into matrices of size @code{[3 3]} before ordinary matrix
subtraction takes place.

A special case of broadcasting that may be familiar is when all
dimensions of the array being broadcast are 1, i.e., the array is a
scalar.  Thus, for example, operations like @code{x - 42} and
@code{max (x, 2)} are basic examples of broadcasting.

For a higher-dimensional example, suppose @code{img} is an RGB image of
size @code{[m n 3]} and we wish to multiply each color by a different
scalar.  The following code accomplishes this with broadcasting,

@example
img .*= permute ([0.8, 0.9, 1.2], [1, 3, 2]);
@end example

@noindent
Note the usage of permute to match the dimensions of the
@code{[0.8, 0.9, 1.2]} vector with @code{img}.

For functions that are not written with broadcasting semantics,
@code{bsxfun} can be useful for coercing them to broadcast.

@c bsxfun libinterp/corefcn/bsxfun.cc
@anchor{XREFbsxfun}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{C} =} bsxfun (@var{f}, @var{A}, @var{B})
Apply a binary function @var{f} element-by-element to two array arguments
@var{A} and @var{B}, expanding singleton dimensions in either input argument as
necessary.

@var{f} is a function handle, inline function, or string containing the name
of the function to evaluate.  The function @var{f} must be capable of accepting
two column-vector arguments of equal length, or one column vector argument and
a scalar.

The dimensions of @var{A} and @var{B} must be equal or singleton.  The
singleton dimensions of the arrays will be expanded to the same dimensionality
as the other array.
@xseealso{@ref{XREFarrayfun,,arrayfun}, @ref{XREFcellfun,,cellfun}}
@end deftypefn


Broadcasting is only applied if either of the two broadcasting
conditions hold.  As usual, however, broadcasting does not apply when two
dimensions differ and neither is 1:

@example
@group
x = [1 2 3
     4 5 6];
y = [10 20
     30 40];
x + y
@end group
@end example

@noindent
This will produce an error about nonconformant arguments.

Besides common arithmetic operations, several functions of two arguments
also broadcast.  The full list of functions and operators that broadcast
is

@example
      plus      +
      minus     -
      times     .*
      rdivide   ./
      ldivide   .\
      power     .^
      lt        <
      le        <=
      eq        ==
      gt        >
      ge        >=
      ne        !=  ~=
      and       &
      or        |
      atan2
      hypot
      max
      min
      mod
      rem
      xor

      +=  -=  .*=  ./=  .\=  .^=  &=  |=
@end example

Here is a real example of the power of broadcasting.  The
@nospell{Floyd-Warshall} algorithm is used to calculate the shortest path
lengths between every pair of vertices in a graph.  A naive implementation for
a graph adjacency matrix of order @var{n} might look like this:

@example
@group
for k = 1:n
  for i = 1:n
    for j = 1:n
      dist(i,j) = min (dist(i,j), dist(i,k) + dist(k,j));
    endfor
  endfor
endfor
@end group
@end example

Upon vectorizing the innermost loop, it might look like this:

@example
@group
for k = 1:n
  for i = 1:n
    dist(i,:) = min (dist(i,:), dist(i,k) + dist(k,:));
  endfor
endfor
@end group
@end example

Using broadcasting in both directions, it looks like this:

@example
@group
for k = 1:n
  dist = min (dist, dist(:,k) + dist(k,:));
endfor
@end group
@end example

The relative time performance of the three techniques for a given graph with
100 vertices is 7.3 seconds for the naive code, 87 milliseconds for the
singly vectorized code, and 1.3 milliseconds for the fully broadcast code.
For a graph with 1000 vertices, vectorization takes 11.7 seconds while
broadcasting takes only 1.15 seconds.  Therefore in general it is worth
writing code with broadcasting semantics for performance.

However, beware of resorting to broadcasting if a simpler operation will
suffice.  For matrices @var{a} and @var{b}, consider the following:

@example
@var{c} = sum (permute (@var{a}, [1, 3, 2]) .* permute (@var{b}, [3, 2, 1]), 3);
@end example

@noindent
This operation broadcasts the two matrices with permuted dimensions
across each other during elementwise multiplication in order to obtain a
larger 3-D array, and this array is then summed along the third dimension.
A moment of thought will prove that this operation is simply the much
faster ordinary matrix multiplication, @code{@var{c} = @var{a}*@var{b};}.

A note on terminology: ``broadcasting'' is the term popularized by the
@nospell{Numpy} numerical environment in the Python programming language.  In
other programming languages and environments, broadcasting may also be known
as @emph{binary singleton expansion} (@nospell{BSX}, in @sc{matlab}, and the
origin of the name of the @code{bsxfun} function), @emph{recycling} (R
programming language), @emph{single-instruction multiple data} (SIMD),
or @emph{replication}.

@node Broadcasting and Legacy Code
@subsection Broadcasting and Legacy Code

The new broadcasting semantics almost never affect code that worked
in previous versions of Octave.  Consequently, all code inherited from
@sc{matlab} that worked in previous versions of Octave should still work
without change in Octave.  The only exception is code such as

@example
@group
try
  c = a.*b;
catch
  c = a.*a;
end_try_catch
@end group
@end example

@noindent
that may have relied on matrices of different size producing an error.
Because such operation is now valid Octave syntax, this will no longer
produce an error.  Instead, the following code should be used:

@example
@group
if (isequal (size (a), size (b)))
  c = a .* b;
else
  c = a .* a;
endif
@end group
@end example


@node Function Application
@section Function Application
@cindex map
@cindex apply
@cindex function application

As a general rule, functions should already be written with matrix
arguments in mind and should consider whole matrix operations in a
vectorized manner.  Sometimes, writing functions in this way appears
difficult or impossible for various reasons.  For those situations,
Octave provides facilities for applying a function to each element of an
array, cell, or struct.

@c arrayfun libinterp/corefcn/cellfun.cc
@anchor{XREFarrayfun}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{B} =} arrayfun (@var{fcn}, @var{A})
@deftypefnx {} {@var{B} =} arrayfun (@var{fcn}, @var{A1}, @var{A2}, @dots{})
@deftypefnx {} {[@var{B1}, @var{B2}, @dots{}] =} arrayfun (@var{fcn}, @var{A}, @dots{})
@deftypefnx {} {@var{B} =} arrayfun (@dots{}, "UniformOutput", @var{val})
@deftypefnx {} {@var{B} =} arrayfun (@dots{}, "ErrorHandler", @var{errfcn})

Execute a function on each element of an array.

This is useful for functions that do not accept array arguments.  If the
function does accept array arguments it is @emph{better} to call the function
directly.

The first input argument @var{fcn} can be a string, a function handle, an
inline function, or an anonymous function.  The input argument @var{A} can be a
logical array, a numeric array, a string array, a structure array, or a cell
array.  @code{arrayfun} passes all elements of @var{A} individually to the
function @var{fcn} and collects the results.  The equivalent pseudo-code is

@example
@group
cls = class (@var{fcn} (@var{A}(1));
@var{B} = zeros (size (@var{A}), cls);
for i = 1:numel (@var{A})
  @var{B}(i) = @var{fcn} (@var{A}(i))
endfor
@end group
@end example

The named function can also take more than two input arguments, with the input
arguments given as third input argument @var{A2}, fourth input argument
@var{A2}, @enddots{}  If given more than one array input argument then all
input arguments must have the same sizes.  For example:

@example
@group
arrayfun (@@atan2, [1, 0], [0, 1])
     @xresult{} [ 1.57080   0.00000 ]
@end group
@end example

If the parameter @var{val} after a further string input argument
@qcode{"UniformOutput"} is set @code{true} (the default), then the named
function @var{fcn} must return a single element which then will be concatenated
into the return value and is of type matrix.  Otherwise, if that parameter is
set to @code{false}, then the outputs are concatenated in a cell array.  For
example:

@example
@group
arrayfun (@@(x,y) x:y, "abc", "def", "UniformOutput", false)
@xresult{}
   @{
     [1,1] = abcd
     [1,2] = bcde
     [1,3] = cdef
   @}
@end group
@end example

If more than one output arguments are given then the named function must return
the number of return values that also are expected, for example:

@example
@group
[A, B, C] = arrayfun (@@find, [10; 0], "UniformOutput", false)
@xresult{}
A =
@{
   [1,1] =  1
   [2,1] = [](0x0)
@}
B =
@{
   [1,1] =  1
   [2,1] = [](0x0)
@}
C =
@{
   [1,1] =  10
   [2,1] = [](0x0)
@}
@end group
@end example

If the parameter @var{errfcn} after a further string input argument
@qcode{"ErrorHandler"} is another string, a function handle, an inline
function, or an anonymous function, then @var{errfcn} defines a function to
call in the case that @var{fcn} generates an error.  The definition of the
function must be of the form

@example
function [@dots{}] = errfcn (@var{s}, @dots{})
@end example

@noindent
where there is an additional input argument to @var{errfcn} relative to
@var{fcn}, given by @var{s}.  This is a structure with the elements
@qcode{"identifier"}, @qcode{"message"}, and @qcode{"index"} giving,
respectively, the error identifier, the error message, and the index of the
array elements that caused the error.  The size of the output argument of
@var{errfcn} must have the same size as the output argument of @var{fcn},
otherwise a real error is thrown.  For example:

@example
@group
function y = ferr (s, x), y = "MyString"; endfunction
arrayfun (@@str2num, [1234],
          "UniformOutput", false, "ErrorHandler", @@ferr)
@xresult{}
   @{
     [1,1] = MyString
   @}
@end group
@end example

@xseealso{@ref{XREFspfun,,spfun}, @ref{XREFcellfun,,cellfun}, @ref{XREFstructfun,,structfun}}
@end deftypefn


@c spfun scripts/sparse/spfun.m
@anchor{XREFspfun}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{y} =} spfun (@var{f}, @var{S})
Compute @code{f (@var{S})} for the nonzero elements of @var{S}.

The input function @var{f} is applied only to the nonzero elements of
the input matrix @var{S} which is typically sparse.  The function @var{f}
can be passed as a string, function handle, or inline function.

The output @var{y} is a sparse matrix with the same sparsity structure as
the input @var{S}.  @code{spfun} preserves sparsity structure which is
different than simply applying the function @var{f} to the sparse matrix
@var{S} when @code{@var{f} (0) != 0}.

Example

Sparsity preserving @code{spfun} versus normal function application

@example
@group
S = pi * speye (2,2)
S =

Compressed Column Sparse (rows = 2, cols = 2, nnz = 2 [50%])

  (1, 1) -> 3.1416
  (2, 2) -> 3.1416

y = spfun (@@cos, S)
y =

Compressed Column Sparse (rows = 2, cols = 2, nnz = 2 [50%])

  (1, 1) -> -1
  (2, 2) -> -1
@end group

@group
y = cos (S)
y =

Compressed Column Sparse (rows = 2, cols = 2, nnz = 4 [100%])

  (1, 1) -> -1
  (2, 1) -> 1
  (1, 2) -> 1
  (2, 2) -> -1

@end group
@end example
@xseealso{@ref{XREFarrayfun,,arrayfun}, @ref{XREFcellfun,,cellfun}, @ref{XREFstructfun,,structfun}}
@end deftypefn


@c cellfun libinterp/corefcn/cellfun.cc
@anchor{XREFcellfun}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{A} =} cellfun (@@@var{fcn}, @var{C})
@deftypefnx {} {@var{A} =} cellfun ("@var{fcn}", @var{C})
@deftypefnx {} {@var{A} =} cellfun (@var{fcn}, @var{C})
@deftypefnx {} {@var{A} =} cellfun (@var{fcn}, @var{C1}, @var{C2}, @dots{})
@deftypefnx {} {[@var{A1}, @var{A2}, @dots{}] =} cellfun (@dots{})
@deftypefnx {} {@var{A} =} cellfun (@dots{}, "UniformOutput", @var{val})
@deftypefnx {} {@var{A} =} cellfun (@dots{}, "ErrorHandler", @var{errfcn})
@deftypefnx {} {@var{A} =} cellfun ('isempty', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('islogical', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('isnumeric', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('isreal', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('length', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('numel', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('prodofsize', @var{C})
@deftypefnx {} {@var{A} =} cellfun ('size', @var{C}, @var{dim})
@deftypefnx {} {@var{A} =} cellfun ('isclass', @var{C}, @var{class})

Evaluate the function @var{fcn} on the elements of the cell array @var{C}.

@code{cellfun} accepts an arbitrary function @var{fcn} given as a name in a
character string, as a function handle, or as an inline function.  Specifying
@var{fcn} with a character string is preferred as the performance is ~3X better
for builtin functions and equivalent for m-files.

@code{cellfun} has a limited number of functions which have been
specially-coded for high-performance (~8X faster than a function handle).
These functions are only used if the function is specified by name as a string,
and only the simplest calling form---@w{@code{cellfun ('@var{fcn}'),
@var{C})}}---without options is supported.  If you need access to an
overloaded version of a function, such as @code{numel} for a particular
@code{classdef} file, then you cannot use the accelerated function name and
must use a function handle instead, e.g., @code{@@numel}.

The high-performance functions are

@table @asis
@item @qcode{'isempty'}
Return true for empty elements.

@item @qcode{'islogical'}
Return true for logical elements.

@item @qcode{'isnumeric'}
Return true for numeric elements.

@item @qcode{'isreal'}
Return true for real elements.

@item @qcode{'length'}
Return a vector of the lengths of cell elements.

@item @qcode{'ndims'}
Return the number of dimensions of each element.

@item  @qcode{'numel'}
@itemx @qcode{'prodofsize'}
Return the number of elements contained within each cell element.  The
number is the product of the dimensions of the object of each cell element.

@item @qcode{'size'}
Return the size along dimension @var{dim}.

@item @qcode{'isclass'}
Return true for elements which are of type @var{class}.
@end table

Elements in @var{C} are passed to the function individually and the result of
each function invocation is collected in the output.  The function can take
more than one argument with the inputs arguments given by @var{C1}, @var{C2},
etc.  Input arguments that are singleton (1x1) cells will be automatically
expanded to the size of the other arguments.  For example:

@example
@group
cellfun ("atan2", @{1, 0@}, @{0, 1@})
     @xresult{} [ 1.57080   0.00000 ]
@end group
@end example

The number of output arguments of @code{cellfun} matches the number of output
arguments of the function and can be greater than one.  When there are multiple
outputs of the function they will be collected into the output arguments of
@code{cellfun} like this:

@example
@group
function [a, b] = twoouts (x)
  a = x;
  b = x*x;
endfunction
[aa, bb] = cellfun (@@twoouts, @{1, 2, 3@})
     @xresult{}
        aa =
           1 2 3
        bb =
           1 4 9
@end group
@end example

Note that, by default, the output argument(s) are arrays of the same size as
the input arguments.

If the parameter @qcode{"UniformOutput"} is set to true (the default), then the
function must return scalars which will be concatenated into the return
array(s).  If @qcode{"UniformOutput"} is false, the outputs are concatenated
into a cell array (or cell arrays).  For example:

@example
@group
cellfun ("lower", @{"Foo", "Bar", "FooBar"@},
         "UniformOutput", false)
@xresult{} @{"foo", "bar", "foobar"@}
@end group
@end example

The parameter @qcode{"ErrorHandler"} specifies a function @var{errfcn} to call
if @var{fcn} generates an error.  The form of the function is

@example
function [@dots{}] = errfcn (@var{s}, @dots{})
@end example

@noindent
where there is an additional input argument to @var{errfcn} relative to
@var{fcn}, given by @var{s}.  This is a structure with the elements
@qcode{"identifier"}, @qcode{"message"}, and @qcode{"index"} giving
respectively the error identifier, the error message, and the index into the
input arguments of the element that caused the error.  For example:

@example
@group
function y = errfcn (s, x), y = NaN; endfunction
cellfun ("factorial", @{-1, 2@}, "ErrorHandler", @@errfcn)
@xresult{} [NaN 2]
@end group
@end example

Programming Note: Use @code{cellfun} intelligently.  The @code{cellfun}
function is a useful tool for avoiding loops.  It is often used with anonymous
function handles; however, calling an anonymous function involves an overhead
quite comparable to the overhead of an m-file function.  Passing a handle to a
built-in function is faster, because the interpreter is not involved in the
internal loop.  For example:

@example
@group
C = @{@dots{}@}
v = cellfun (@@(x) det (x), C); # compute determinants
v = cellfun (@@det, C);         # 40% faster
@end group
@end example

@xseealso{@ref{XREFarrayfun,,arrayfun}, @ref{XREFstructfun,,structfun}, @ref{XREFspfun,,spfun}}
@end deftypefn


@c structfun scripts/general/structfun.m
@anchor{XREFstructfun}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{A} =} structfun (@var{fcn}, @var{S})
@deftypefnx {} {@var{A} =} structfun (@dots{}, "ErrorHandler", @var{errfcn})
@deftypefnx {} {@var{A} =} structfun (@dots{}, "UniformOutput", @var{val})
@deftypefnx {} {[@var{A}, @var{B}, @dots{}] =} structfun (@dots{})

Evaluate the function named @var{name} on the fields of the structure
@var{S}.  The fields of @var{S} are passed to the function @var{fcn}
individually.

@code{structfun} accepts an arbitrary function @var{fcn} in the form of an
inline function, function handle, or the name of a function (in a character
string).  In the case of a character string argument, the function must
accept a single argument named @var{x}, and it must return a string value.
If the function returns more than one argument, they are returned as
separate output variables.

If the parameter @qcode{"UniformOutput"} is set to true (the default), then
the function must return a single element which will be concatenated into
the return value.  If @qcode{"UniformOutput"} is false, the outputs are
placed into a structure with the same fieldnames as the input structure.

@example
@group
s.name1 = "John Smith";
s.name2 = "Jill Jones";
structfun (@@(x) regexp (x, '(\w+)$', "matches")@{1@}, s,
           "UniformOutput", false)
  @xresult{} scalar structure containing the fields:
       name1 = Smith
       name2 = Jones
@end group
@end example

Given the parameter @qcode{"ErrorHandler"}, @var{errfcn} defines a function
to call in case @var{fcn} generates an error.  The form of the function is

@example
function [@dots{}] = errfcn (@var{se}, @dots{})
@end example

@noindent
where there is an additional input argument to @var{errfcn} relative to
@var{fcn}, given by @nospell{@var{se}}.  This is a structure with the
elements @qcode{"identifier"}, @qcode{"message"} and @qcode{"index"},
giving respectively the error identifier, the error message, and the index
into the input arguments of the element that caused the error.  For an
example on how to use an error handler, @pxref{XREFcellfun,,@code{cellfun}}.

@xseealso{@ref{XREFcellfun,,cellfun}, @ref{XREFarrayfun,,arrayfun}, @ref{XREFspfun,,spfun}}
@end deftypefn


Consistent with earlier advice, seek to use Octave built-in functions whenever
possible for the best performance.  This advice applies especially to the four
functions above.  For example, when adding two arrays together
element-by-element one could use a handle to the built-in addition function
@code{@@plus} or define an anonymous function @code{@@(x,y) x + y}.  But, the
anonymous function is 60% slower than the first method.
@xref{Operator Overloading}, for a list of basic functions which might be used
in place of anonymous ones.

@node Accumulation
@section Accumulation

Whenever it's possible to categorize according to indices the elements
of an array when performing a computation, accumulation functions can be
useful.

@c accumarray scripts/general/accumarray.m
@anchor{XREFaccumarray}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{A} =} accumarray (@var{subs}, @var{vals})
@deftypefnx {} {@var{A} =} accumarray (@var{subs}, @var{vals}, @var{sz})
@deftypefnx {} {@var{A} =} accumarray (@var{subs}, @var{vals}, @var{sz}, @var{fcn})
@deftypefnx {} {@var{A} =} accumarray (@var{subs}, @var{vals}, @var{sz}, @var{fcn}, @var{fillval})
@deftypefnx {} {@var{A} =} accumarray (@var{subs}, @var{vals}, @var{sz}, @var{fcn}, @var{fillval}, @var{issparse})

Create an array by accumulating the elements of a vector into the
positions defined by their subscripts.

The subscripts are defined by the rows of the matrix @var{subs} and the
values by @var{vals}.  Each row of @var{subs} corresponds to one of the
values in @var{vals}.  If @var{vals} is a scalar, it will be used for each
of the row of @var{subs}.  If @var{subs} is a cell array of vectors, all
vectors must be of the same length, and the subscripts in the @var{k}th
vector must correspond to the @var{k}th dimension of the result.

The size of the matrix will be determined by the subscripts
themselves.  However, if @var{sz} is defined it determines the matrix
size.  The length of @var{sz} must correspond to the number of columns
in @var{subs}.  An exception is if @var{subs} has only one column, in
which case @var{sz} may be the dimensions of a vector and the
subscripts of @var{subs} are taken as the indices into it.

The default action of @code{accumarray} is to sum the elements with
the same subscripts.  This behavior can be modified by defining the
@var{fcn} function.  This should be a function or function handle
that accepts a column vector and returns a scalar.  The result of the
function should not depend on the order of the subscripts.

The elements of the returned array that have no subscripts associated
with them are set to zero.  Defining @var{fillval} to some other value
allows these values to be defined.  This behavior changes, however,
for certain values of @var{fcn}.  If @var{fcn} is @code{@@min}
(respectively, @code{@@max}) then the result will be filled with the
minimum (respectively, maximum) integer if @var{vals} is of integral
type, logical false (respectively, logical true) if @var{vals} is of
logical type, zero if @var{fillval} is zero and all values are
non-positive (respectively, non-negative), and NaN otherwise.

By default @code{accumarray} returns a full matrix.  If
@var{issparse} is logically true, then a sparse matrix is returned
instead.

The following @code{accumarray} example constructs a frequency table
that in the first column counts how many occurrences each number in
the second column has, taken from the vector @var{x}.  Note the usage
of @code{unique}  for assigning to all repeated elements of @var{x}
the same index (@pxref{XREFunique,,@code{unique}}).

@example
@group
@var{x} = [91, 92, 90, 92, 90, 89, 91, 89, 90, 100, 100, 100];
[@var{u}, ~, @var{j}] = unique (@var{x});
[accumarray(@var{j}', 1), @var{u}']
  @xresult{}  2    89
      3    90
      2    91
      2    92
      3   100
@end group
@end example

Another example, where the result is a multi-dimensional 3-D array and
the default value (zero) appears in the output:

@example
@group
accumarray ([1, 1, 1;
             2, 1, 2;
             2, 3, 2;
             2, 1, 2;
             2, 3, 2], 101:105)
@xresult{} ans(:,:,1) = [101, 0, 0; 0, 0, 0]
@xresult{} ans(:,:,2) = [0, 0, 0; 206, 0, 208]
@end group
@end example

The sparse option can be used as an alternative to the @code{sparse}
constructor (@pxref{XREFsparse,,@code{sparse}}).  Thus

@example
sparse (@var{i}, @var{j}, @var{sv})
@end example

@noindent
can be written with @code{accumarray} as

@example
accumarray ([@var{i}, @var{j}], @var{sv}', [], [], 0, true)
@end example

@noindent
For repeated indices, @code{sparse} adds the corresponding value.  To
take the minimum instead, use @code{min} as an accumulator function:

@example
accumarray ([@var{i}, @var{j}], @var{sv}', [], @@min, 0, true)
@end example

The complexity of accumarray in general for the non-sparse case is
generally O(M+N), where N is the number of subscripts and M is the
maximum subscript (linearized in multi-dimensional case).  If
@var{fcn} is one of @code{@@sum} (default), @code{@@max},
@code{@@min} or @code{@@(x) @{x@}}, an optimized code path is used.
Note that for general reduction function the interpreter overhead can
play a major part and it may be more efficient to do multiple
accumarray calls and compute the results in a vectorized manner.

@xseealso{@ref{XREFaccumdim,,accumdim}, @ref{XREFunique,,unique}, @ref{XREFsparse,,sparse}}
@end deftypefn


@c accumdim scripts/general/accumdim.m
@anchor{XREFaccumdim}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{A} =} accumdim (@var{subs}, @var{vals})
@deftypefnx {} {@var{A} =} accumdim (@var{subs}, @var{vals}, @var{dim})
@deftypefnx {} {@var{A} =} accumdim (@var{subs}, @var{vals}, @var{dim}, @var{n})
@deftypefnx {} {@var{A} =} accumdim (@var{subs}, @var{vals}, @var{dim}, @var{n}, @var{fcn})
@deftypefnx {} {@var{A} =} accumdim (@var{subs}, @var{vals}, @var{dim}, @var{n}, @var{fcn}, @var{fillval})
Create an array by accumulating the slices of an array into the
positions defined by their subscripts along a specified dimension.

The subscripts are defined by the index vector @var{subs}.
The dimension is specified by @var{dim}.  If not given, it defaults
to the first non-singleton dimension.  The length of @var{subs} must
be equal to @code{size (@var{vals}, @var{dim})}.

The extent of the result matrix in the working dimension will be
determined by the subscripts themselves.  However, if @var{n} is
defined it determines this extent.

The default action of @code{accumdim} is to sum the subarrays with the
same subscripts.  This behavior can be modified by defining the
@var{fcn} function.  This should be a function or function handle
that accepts an array and a dimension, and reduces the array along
this dimension.  As a special exception, the built-in @code{min} and
@code{max} functions can be used directly, and @code{accumdim}
accounts for the middle empty argument that is used in their calling.

The slices of the returned array that have no subscripts associated
with them are set to zero.  Defining @var{fillval} to some other
value allows these values to be defined.

An example of the use of @code{accumdim} is:

@example
@group
accumdim ([1, 2, 1, 2, 1], [ 7, -10,   4;
                            -5, -12,   8;
                           -12,   2,   8;
                           -10,   9,  -3;
                            -5,  -3, -13])
@xresult{} [-10,-11,-1;-15,-3,5]
@end group
@end example

@xseealso{@ref{XREFaccumarray,,accumarray}}
@end deftypefn


@node Memoization
@section Memoization

Memoization is a technique to cache the results of slow function calls and
return the cached value when the function is called with the same inputs again,
instead of reevaluating it.  It is very common to replace function calls with
lookup tables if the same inputs are happening over and over again in a known,
predictable way.  Memoization is, at its core, an extension of this practice
where the lookup table is extended even during runtime for new arguments not
seen previously.  A basic theoretical background can be found on Wikipedia or
any undergraduate-level computer science textbook.

Octave's @code{memoize} function provides drop-in memoization functionality for
any user function or Octave function, including compiled functions.

@c memoize scripts/miscellaneous/memoize.m
@anchor{XREFmemoize}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{mem_fcn_handle} =} memoize (@var{fcn_handle})

Create a memoized version @var{mem_fcn_handle} of function @var{fcn_handle}.

Each call to the memoized version @var{mem_fcn_handle} checks the inputs
against an internally maintained table, and if the inputs have occurred
previously, then the result of the function call is returned from the table
itself instead of evaluating the full function again.  This speeds up the
execution of functions that are called with the same inputs multiple times.

For example, here we take a slow user-written function named @code{slow_fcn}
and memoize it to a new handle @code{cyc}.  The first executions of both
versions take the same time, but the subsequent executions of the memoized
version returns the previously computed value, thus reducing 2.4 seconds of
runtime to only 2.4 milliseconds.  The final check verifies that the same
result was returned from both versions.

@example
@group
>> tic; @var{p} = slow_fcn (5040); toc
Elapsed time is 2.41244 seconds.
>> tic; @var{p} = slow_fcn (5040); toc
Elapsed time is 2.41542 seconds.

>> cyc = memoize (@@slow_fcn);
>> tic; @var{r} = cyc (5040); toc
Elapsed time is 2.42609 seconds.
>> tic; @var{r} = cyc (5040); toc
Elapsed time is 0.00236511 seconds.

>> all (@var{p} == @var{r})
ans = 1
@end group
@end example

@xseealso{@ref{XREFclearAllMemoizedCaches,,clearAllMemoizedCaches}}
@end deftypefn


To memoize a function @code{z = foo(x, y)}, use this general pattern:

@example
@group
foo2 = memoize (@@(@var{x, y}) @var{foo(x, y)});
z = foo2 (x, y);
@end group
@end example

In the above example, the first line creates a memoized version @code{foo2} of
the function @code{foo}.  For simple functions with only trivial wrapping, this
line can also be shortened to:

@example
@group
foo2 = memoize (@@foo);
@end group
@end example

The second line @code{z = foo2 (x, y);} calls that memoized version @code{foo2}
instead of the original function, allowing @code{memoize} to intercept the call
and replace it with a looked-up value from a table if the inputs have occurred
before, instead of evaluating the original function again.

Note that this will not accelerate the @emph{first} call to the function but
only subsequent calls.

Note that due to the overhead incurred by @code{memoize} to create and manage
the lookup tables for each function, this technique is useful only for
functions that take at least a couple of seconds to execute.  Such functions
can be replaced by table lookups taking only a millisecond or so, but if the
original function itself was taking only milliseconds, memoizing it will not
speed it up.

Recursive functions can be memoized as well, using a pattern like:

@example
@group
function z = foo (x, y)
  persistent foo2 = memoize (@@foo);
  foo2.CacheSize = 1e6;

  ## Call the memoized version when recursing
  z = foo2 (x, y);
endfunction
@end group
@end example

The @code{CacheSize} can be optionally increased in anticipation of a large
number of function calls, such as from inside a recursive function.  If
@code{CacheSize} is exceeded, the memoization tables are resized, causing a
slowdown.  Increasing the @code{CacheSize} thus works like preallocation to
speed up execution.

The function @code{clearAllMemoizedCaches} clears the memoization tables when
they are no longer needed.

@c clearAllMemoizedCaches scripts/miscellaneous/clearAllMemoizedCaches.m
@anchor{XREFclearAllMemoizedCaches}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {} clearAllMemoizedCaches ()
Clear all memoized caches.

Memoization maintains internal tables of which functions have been called
with which inputs.  This function clears those tables to free memory,
or for a fresh start.

@xseealso{@ref{XREFmemoize,,memoize}}
@end deftypefn


@node Miscellaneous Techniques
@section Miscellaneous Techniques
@cindex execution speed
@cindex speedups
@cindex optimization

Here are some other ways of improving the execution speed of Octave programs.

@itemize @bullet

@item Avoid computing costly intermediate results multiple times.
Octave currently does not eliminate common subexpressions.  Also, certain
internal computation results are cached for variables.  For instance, if
a matrix variable is used multiple times as an index, checking the
indices (and internal conversion to integers) is only done once.

@item Be aware of lazy copies (copy-on-write).
@cindex copy-on-write
@cindex COW
@cindex memory management
When a copy of an object is created, the data is not immediately copied, but
rather shared.  The actual copying is postponed until the copied data needs to
be modified.  For example:

@example
@group
a = zeros (1000); # create a 1000x1000 matrix
b = a; # no copying done here
b(1) = 1; # copying done here
@end group
@end example

Lazy copying applies to whole Octave objects such as matrices, cells,
struct, and also individual cell or struct elements (not array
elements).

Additionally, index expressions also use lazy copying when Octave can
determine that the indexed portion is contiguous in memory.  For example:

@example
@group
a = zeros (1000); # create a 1000x1000 matrix
b = a(:,10:100);  # no copying done here
b = a(10:100,:);  # copying done here
@end group
@end example

This applies to arrays (matrices), cell arrays, and structs indexed
using @samp{()}.  Index expressions generating comma-separated lists can also
benefit from shallow copying in some cases.  In particular, when @var{a} is a
struct array, expressions like @code{@{a.x@}, @{a(:,2).x@}} will use lazy
copying, so that data can be shared between a struct array and a cell array.

Most indexing expressions do not live longer than their parent
objects.  In rare cases, however, a lazily copied slice outlasts its
parent, in which case it becomes orphaned, still occupying unnecessarily
more memory than needed.  To provide a remedy working in most real cases,
Octave checks for orphaned lazy slices at certain situations, when a
value is stored into a "permanent" location, such as a named variable or
cell or struct element, and possibly economizes them.  For example:

@example
@group
a = zeros (1000); # create a 1000x1000 matrix
b = a(:,10:100);  # lazy slice
a = []; # the original "a" array is still allocated
c@{1@} = b; # b is reallocated at this point
@end group
@end example

@item Avoid deep recursion.
Function calls to m-file functions carry a relatively significant overhead, so
rewriting a recursion as a loop often helps.  Also, note that the maximum level
of recursion is limited.

@item Avoid resizing matrices unnecessarily.
When building a single result matrix from a series of calculations, set the
size of the result matrix first, then insert values into it.  Write

@example
@group
result = zeros (big_n, big_m)
for i = over:and_over
  ridx = @dots{}
  cidx = @dots{}
  result(ridx, cidx) = new_value ();
endfor
@end group
@end example

@noindent
instead of

@example
@group
result = [];
for i = ever:and_ever
  result = [ result, new_value() ];
endfor
@end group
@end example

Sometimes the number of items can not be computed in advance, and
stack-like operations are needed.  When elements are being repeatedly
inserted or removed from the end of an array, Octave detects it as stack
usage and attempts to use a smarter memory management strategy by
pre-allocating the array in bigger chunks.  This strategy is also applied
to cell and struct arrays.

@example
@group
a = [];
while (condition)
  @dots{}
  a(end+1) = value; # "push" operation
  @dots{}
  a(end) = []; # "pop" operation
  @dots{}
endwhile
@end group
@end example

@item Avoid calling @code{eval} or @code{feval} excessively.
Parsing input or looking up the name of a function in the symbol table are
relatively expensive operations.

If you are using @code{eval} merely as an exception handling mechanism, and not
because you need to execute some arbitrary text, use the @code{try}
statement instead.  @xref{The try Statement}.

@item Use @code{ignore_function_time_stamp} when appropriate.
If you are calling lots of functions, and none of them will need to change
during your run, set the variable @code{ignore_function_time_stamp} to
@qcode{"all"}.  This will stop Octave from checking the time stamp of a
function file to see if it has been updated while the program is being run.
@end itemize

@node Examples
@section Examples

The following are examples of vectorization questions asked by actual
users of Octave and their solutions.

@c FIXME: We need a lot more examples here.

@itemize @bullet
@item
For a vector @code{A}, the following loop

@example
@group
n = length (A) - 1;
B = zeros (n, 2);
for i = 1:n
  ## this will be two columns, the first is the difference and
  ## the second the mean of the two elements used for the diff.
  B(i,:) = [A(i+1)-A(i), (A(i+1) + A(i))/2];
endfor
@end group
@end example

@noindent
can be turned into the following one-liner:

@example
B = [diff(A)(:), 0.5*(A(1:end-1)+A(2:end))(:)]
@end example

Note the usage of colon indexing to flatten an intermediate result into
a column vector.  This is a common vectorization trick.

@end itemize
