How to create a n to n matrix in python with input value diagonal

Question:

I am working on a probabilistic calculation and I could run my code for a small matrix like;

P_4 = np.array([
    
     [0  ,1  ,0  ,  0,  0],
     [0  ,1/4,3/4,  0,  0],
     [0  ,0  ,2/4,2/4,  0],
     [0  ,0  ,0  ,3/4,1/4],
     [0  ,0  ,0  ,  0,1  ],
   
])

However, I would like to create a N*N matrix and to fill the values diagonally 0/n and next value 1 – 0/n.

n = 5

a = np.zeros((n,n),dtype = int)

np.fill_diagonal(a,np.array([range(1/n)]))

a

writing the above code gives me the error

TypeError: 'float' object cannot be interpreted as an integer

I would a appreciate any suggestions.

Asked By: Ahmad Morwat

||

Answers:

Here’s one option using linspace and diag.

n = 5
diag = np.linspace(0, 1, n)
diag1 = (1 - diag[:-1])
a = np.diag(diag) + np.diag(diag1, 1)
a

Output:

array([[0.  , 1.  , 0.  , 0.  , 0.  ],
       [0.  , 0.25, 0.75, 0.  , 0.  ],
       [0.  , 0.  , 0.5 , 0.5 , 0.  ],
       [0.  , 0.  , 0.  , 0.75, 0.25],
       [0.  , 0.  , 0.  , 0.  , 1.  ]])
Answered By: BigBen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.