GNU Octave method to operate on each item in a matrix. octave "arrayfun(...)" example

Eric Leschinski picture Eric Leschinski · Jul 8, 2012 · Viewed 19.7k times · Source

In GNU Octave version 3.4.3, I am having trouble applying a custom function to operate on each item/element in a matrix.

I have a (2,3) matrix that looks like:

mymatrix = [1,2,3;4,5,6];

mymatrix

   1   2   3
   4   5   6

I want to use each element of the matrix as an input, and run a custom function against it, and have the output of the function replace the content of mymatrix item by item.

Answer

Nikita G. picture Nikita G. · Oct 17, 2014

arrayfun works well for this:

arrayfun(@(x) 1/(1+e^(-x)), [0, 1; 2, 3])

Output:

ans =

   0.50000   0.73106
   0.88080   0.95257

This basically runs function 1/(1+e^(-x)) on each element of the matrix/vector.