Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null matrix with constant diagonal, with same shape as another matrix

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.

like image 616
Arjun Nayini Avatar asked May 02 '11 00:05

Arjun Nayini


People also ask

Can a null matrix be a diagonal matrix?

Statement 1: Every null matrix of order n is a diagonal matrix. ∵ All the principal diagonal elements of matrix O are zero which violates the definition of a diagonal matrix. As for a diagonal matrix all the elements are zero except those in the principal diagonal. Hence, statement 1 is false.

Can a diagonal matrix have a zero of the diagonal?

A diagonal matrix is defined as a square matrix in which all off-diagonal entries are zero. (Note that a diagonal matrix is necessarily symmetric.) Entries on the main diagonal may or may not be zero.

When all diagonal elements are equal to one then this matrix is?

An identity matrix is a diagonal matrix in which all of the diagonal elements are equal to . No worries!

When all diagonal elements of a matrix are equal to unity and other elements are zero the matrix is called?

It is given that a unit matrix is a diagonal matrix in which all the diagonal elements are unity and all the other elements are zero. And all the other elements are equal to zero. Hence, the given statement, i.e. Unit matrix is a diagonal matrix in which all the diagonal elements are unity.


1 Answers

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)
like image 75
Eric O Lebigot Avatar answered Oct 12 '22 11:10

Eric O Lebigot