I am pritty new to Julia and try to find my first steps. I am a bit confused now.
In Python I had this (simplyfied) piece of code:
import numpy as np
a = [[1,2], [3,4]]
M = np.array(a)
It brings me the expected result:
[0.99505475, 0.9993293 ]])
Now I try my luck with Julia:
M = [1 2
My question, what is calculated here?
However if I do:
I get the expected result again. I think I understand concept of “.” as the elementwise operator. But I thought tanh() and similar are always elementwise. If I am wrong, what is tanh(M) without “.” calculating?
In julia, any operation on a matrix will not be element-wise unless you have a
.. It turns out that for square matrices, you can take a hyperbolic tangent of a matrix. That’s the result you are seeing when you type
1.1667362572409197 - 0.24345820118572525im
julia> tanh([1 -2; 2 1])
As Oscar_Smith said, the component-wise
tanh and (diagonalizable, square) matrix
tanh are different in general. The matrix
tanh is derived from a power series expansion of the scalar tanh, where the scalar powers are replaced with matrix powers. It can be computed by taking the eigenvalue decomposition
U*diagm(evals)*U' of the matrix, taking the component-wise
tanh on the eigenvalues, and then reconstructing:
julia> A = [1 -2; 2 1]
julia> using LinearAlgebra
julia> evals, U = eigen(A)
1.0 - 2.0000000000000004im
1.0 + 2.0000000000000004im
The last line gives an example where the component-wise and matrix versions of
Provided that the matrix is diagonalizable, of course.
Yes, thanks for reminding us that the power series derivation of
tanh(A) requires diagonalizability of
A. But my demo used the decomposition
A=U*diagm(evals)*U', so we need to further assume that
A is unitarily diagonalizable for that to work, i.e., the transpose
U' is also the inverse of
U, which occurs when
A is normal (
A*A' == A'*A). It’s sufficient that
A is (real) symmetric for normality to hold.