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.
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.
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).
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.
Alternatively you can use the element-wise operators like the following (note the dot prefix):
For example
mymatrix = 1 ./ (1 .+ e.^(-mymatrix));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With