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.
CodePudding user response:
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. ]])