19.7 Examples

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

  • For a vector A, the following loop
    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

    can be turned into the following one-liner:

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

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

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Examples.html