添加一个矩阵的倍数而不建立一个新的矩阵 [英] Add multiple of a matrix without build a new one

查看:188
本文介绍了添加一个矩阵的倍数而不建立一个新的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个矩阵BM,我想执行以下语句:

Say I have two matrices B and M and I want to execute the following statement:

B += 3*M

我重复执行此指令,所以我不想每次都构建矩阵3*M(3可能会改变,只是为了安慰我只做一个标量矩阵乘积).是使该计算就地"的numpy函数吗?

I execute this instruction repeatedly so I don't want to build each time the matrix 3*M (3 may change, it is just to make cleat that I only do a scalar-matrix product). Is it a numpy-function which makes this computation "in place"?

更确切地说,我有一个标量as列表和一个矩阵Ms列表,我想执行点积"(由于两个操作数的类型不同,所以实际上不是一个)这两个,就是说:

More precisely, I have a list of scalars as and a list of matrices Ms, I would like to perform the "dot product" (which is not really one since the two operands are of different type) of the two, that is to say:

sum(a*M for a, M in zip(as, Ms))

np.dot函数除了我没有做......

The np.dot function does not do what I except...

推荐答案

您可以使用 np.tensordot -

You can use np.tensordot -

np.tensordot(As,Ms,axes=(0,0))

np.einsum -

np.einsum('i,ijk->jk',As,Ms)

样品运行-

In [41]: As = [2,5,6]

In [42]: Ms = [np.random.rand(2,3),np.random.rand(2,3),np.random.rand(2,3)]

In [43]: sum(a*M for a, M in zip(As, Ms))
Out[43]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])

In [44]: np.tensordot(As,Ms,axes=(0,0))
Out[44]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])

In [45]: np.einsum('i,ijk->jk',As,Ms)
Out[45]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])

这篇关于添加一个矩阵的倍数而不建立一个新的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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