Null matrix with constant diagonal, with same shape as another matrix
Solution 1
If you want a matrix with 40 on the diagonal and zeros everywhere else, you can use NumPy's function fill_diagonal()
on a matrix of zeros. You can thus directly do:
N = 100; value = 40
b = np.zeros((N, N))
np.fill_diagonal(b, value)
This involves only setting elements to a certain value, and is therefore likely to be faster than code involving multiplying all the elements of a matrix by a constant. This approach also has the advantage of showing explicitly that you fill the diagonal with a specific value.
If you want the diagonal matrix b
to be of the same size as another matrix a
, you can use the following shortcut (no need for an explicit size N
):
b = np.zeros_like(a)
np.fill_diagonal(b, value)
Solution 2
Easy:
N = 100
a = np.eye(N) # Diagonal Identity 100x100 array
b = 40*a # Multiply by a scalar
If you actually want a numpy matrix vs an array, you can do a = np.asmatrix(np.eye(N))
instead. But in general *
is element-wise multiplication in numpy.
Related videos on Youtube
Arjun Nayini
Updated on May 31, 2022Comments
-
Arjun Nayini almost 2 years
I'm wondering if there is a simple way to multiply a numpy matrix by a scalar. Essentially I want all values to be multiplied by the constant 40. This would be an nxn matrix with 40's on the diagonal, but I'm wondering if there is a simpler function to use to scale this matrix. Or how would I go about making a matrix with the same shape as my other matrix and fill in its diagonal?
Sorry if this seems a bit basic, but for some reason I couldn't find this in the doc.
-
carboleda almost 13 yearsIf performance is an issue, the OP may not want to create a copy
b
, in which casea*=40
will scale the array in-place. -
Bruno Feroleto about 11 years
numpy.fill_diagonal()
is specifically meant to fill the diagonal with a given element. As a consequence, it is more explicit and faster than constructing the identity matrix and then multiplying all its elements by a constant.