Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 209
Eric Leschinski Avatar asked Jul 08 '12 21:07

Eric Leschinski


People also ask

How do you initialize a matrix in Octave?

Matrices are entered row by row using the same syntax as for vectors. To interchange rows with columns, that is, to find the transpose of a vector or a matrix, use the apostrophe. For example, the command octave#:#> C = [4 7.5 -1]' will transform the row vector C = [4 7.5 -1] into a column vector.

What are the Octave commands?

Entering commands The last line above is known as the Octave prompt and, much like the prompt in Linux, this is where you type Octave commands. To do simple arithmetic, use + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation).


2 Answers

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.

like image 190
Nikita R. Avatar answered Oct 15 '22 11:10

Nikita R.


Alternatively you can use the element-wise operators like the following (note the dot prefix):

  • .+
  • .-
  • ./
  • e.^

For example

mymatrix = 1 ./ (1 .+ e.^(-mymatrix)); 
like image 20
frhack Avatar answered Oct 15 '22 09:10

frhack