Numpy array wrong dimensions with calculations
I have a matrix
import numpy as np
A = np.array([[.7,.2,.1],[0,.6,.4],[.5,0,.5]]);A
I want to make a function that calculate a stationarity :
def statdist(A):
m = A.shape[0]
s = (m,m)
I = np.identity(3)
return( np.ones(m)@np.linalg.inv(I)- A+np.ones(s))
statdist(A)
The result must be
0.4761905 0.2380952 0.2857143
but the output from python is a matrix:
array([[1.3, 1.8, 1.9],
[2. , 1.4, 1.6],
[1.5, 2. , 1.5]])
What I make wrong ?
In R is simple right :
statdist <- function(gamma){
m = dim(gamma)[1]
matrix(1,1,m) %*% solve(diag(1,m) - gamma + matrix(1,m,m))
}
i = matrix(c(.7,.2,.1,0,.6,.4,.5,0,.5),3,3,byrow = TRUE);i
statdist(i)
A
is (3,3)
m = A.shape[0] # 3
s = (m,m)
I = np.identity(3) # (3,3)
return( np.ones(m)@np.linalg.inv(I)- A+np.ones(s))
in the last line
(3,) @ (3,3) => (3,3)
(3,3) - (3,3) + (3,) => (3,3)
oops
(3,) @ (3,3) => (3,)
(3,) - (3,3) + (3,3) => (3,3)
with the suggested change
np.ones(m)@np.linalg.inv(I- A+np.ones(s))
(3,3)-(3,3)+(3,3) => (3,3)
(3,) @ (3,3) => (3,)
With the numbers:
In [621]: A = np.array([[.7,.2,.1],[0,.6,.4],[.5,0,.5]])
In [622]: np.ones(3)@np.linalg.inv(np.eye(3)- A+np.ones((3,3)))
Out[622]: array([0.47619048, 0.23809524, 0.28571429])