具有恒定对角线的零矩阵,形状与另一个矩阵相同 [英] Null matrix with constant diagonal, with same shape as another matrix

查看:113
本文介绍了具有恒定对角线的零矩阵,形状与另一个矩阵相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种简单的方法将numpy矩阵乘以标量.本质上,我希望所有值都乘以常数40.这将是对角线为40的nxn矩阵,但是我想知道是否有更简单的函数来缩放该矩阵.还是我将如何制作形状与其他矩阵相同的矩阵并填写其对角线?

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.

推荐答案

如果您想要对角线为40且在其他所有位置为零的矩阵,则可以在零矩阵上使用NumPy函数fill_diagonal().因此,您可以直接执行以下操作:

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.

如果您希望对角矩阵b与另一个矩阵a具有相同的大小,则可以使用以下快捷方式(不需要明确的大小N):

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)

这篇关于具有恒定对角线的零矩阵,形状与另一个矩阵相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆