Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: fill offset diagonal with different values

Tags:

python

numpy

I need to make a n*n matrix m whose elements follow m(i,i+1)=sqrt(i) and 0 otherwise. For example, for n=5, we should have

[0 a 0 0 0]
[0 0 b 0 0]
[0 0 0 c 0]
[0 0 0 0 d]
[0 0 0 0 0]

where {a,b,c,d}=sqrt({1,2,3,4}). Here is a solution for a constant tri-diagonal matrix, but my case is a bit more complicated than that. I know I can do that with a loop or with list comprehension, but are there other ways? n can be potentially big.

e.g. (list comprehension code)

ele=lambda i,j:sqrt(i+1) if j-i==1 else 0

[[ele(i,j) for j in range(0,6)] for i in range(0,6)]
like image 555
egwene sedai Avatar asked May 27 '15 15:05

egwene sedai


People also ask

How do you fill a diagonal array in Python?

With the help of numpy. fill_diagonal() method, we can get filled the diagonals of numpy array with the value passed as the parameter in numpy. fill_diagonal() method. Return : Return the filled value in the diagonal of an array.

How do you print diagonal elements of a matrix in Python using NumPy?

diagonal() With the help of Numpy matrix. diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix.


1 Answers

One way could be to create the array of zeros and then use indexing to select and fill the desired indices with the square-root values.

For example:

>>> z = np.zeros((5,5))
>>> rng = np.arange(4)
>>> z[rng, rng+1] = np.sqrt(rng+1)
>>> z
array([[ 0.        ,  1.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  1.41421356,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  1.73205081,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  2.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])
like image 60
Alex Riley Avatar answered Sep 17 '22 15:09

Alex Riley