Octave Programming Tutorial/Vectorization

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Writing routines in terms of vector operations can be orders of magnitudes more efficient than using built-in interpretted loops because Octave can make use of highly optimized FORTRAN and C numerical linear algebra libraries instead. Even if a routine or function is not written in a vectorized form, it is possible to take advantage of vectorization by using arrayfun or a similar structure.

vectorizing a regular function with arrayfun[edit]

Consider an anonymous function

octave:1> f = @(x) sin(x)*x

Octave output :

f =
@(x) sin (x)*x

and assume that we want to calculate this function for every element of a given vector of integers from 1 to 7 :

octave:2> y=1:7
y =
  1   2   3   4   5   6   7

then passing y as an argument for f will give error

octave:3> f(y)
error: operator *: nonconformant arguments (op1 is 1x7, op2 is 1x7)
error: called from:
error:    at line -1, column -1

this is because f is not defined for a vector input. But this is not a problem as we can do:

octave:4> arrayfun(f,y)

and output is :

ans =
  0.84147   1.81859   0.42336  -3.02721  -4.79462  -1.67649   4.59891

This is an order of magnitude faster than calculating f for many y values by using a loop which has a big overhead.