14

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.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Arjun Nayini
  • 191
  • 1
  • 2
  • 5

2 Answers2

17

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)
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
9

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.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
JoshAdel
  • 66,734
  • 27
  • 141
  • 140
  • 3
    If performance is an issue, the OP may not want to create a copy `b`, in which case `a*=40` will scale the array in-place. – Paul May 02 '11 at 01:11
  • `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. – Eric O. Lebigot Apr 09 '13 at 02:41