Reputation: 3381
For the purpose of this exercise, let's consider a matrix where the element m_{i, j}
is given by the rule m_{i, j} = i*j
if i == j
and 0
else.
Is there an easy "numpy" way of calculating such a matrix without having to resort to if
statements checking for the indices?
Upvotes: 0
Views: 2808
Reputation: 8585
Assuming you have a squared matrix, you can do this:
import numpy as np
ary = np.zeros((4, 4))
_ = [ary.__setitem__((i, i), i**2) for i in range(ary.shape[0])]
print(ary)
# array([[0., 0., 0., 0.],
# [0., 1., 0., 0.],
# [0., 0., 4., 0.],
# [0., 0., 0., 9.]])
Upvotes: 0
Reputation: 308
You could use the identity matrix given by numpy.identity(n)
and then multiply it by a n
dimensional vector.
Upvotes: 0
Reputation: 436
You can use the numpy function diag
to construct a diagonal matrix if you give it the intended diagonal as a 1D array as input.
So you just need to create that, like [i**2 for i in range (N)]
with N
the dimension of the matrix.
Upvotes: 1