0

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)
4
  • Check the dimensions of every element in the return statement. The first term is a 1d vector whose shape is (3,) , while the second one - A+np.ones(s) is a sum of two 3x3 matrices. Commented Jan 21, 2022 at 23:01
  • 2
    Parentheses in the return value seem to be misplaced. It should be np.ones(m)@np.linalg.inv(I- A+np.ones(s)) Commented Jan 21, 2022 at 23:07
  • np.ones(m).reshape((1,m) is (3,1) but still the result is wrong Commented Jan 21, 2022 at 23:07
  • 1
    @bb1 you are right thanks mate I didn't see that Commented Jan 21, 2022 at 23:08

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

See @bb1's post in the main comments. The return has a misplaced parenthesis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.