numpy:广播矩阵乘以整个数组 [英] numpy: broadcast matrix multiply accross array

查看:109
本文介绍了numpy:广播矩阵乘以整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3xN数组,从概念上讲是一个N 3个向量的数组,我想构造一个 数组,该矩阵是通过将给定的3x3矩阵与矩阵的每一列相乘而得到的 大批.有矢量的方式来做到这一点的好方法吗?

I have a 3xN array, conceptually an array of N 3-vectors, I want to construct the array which results from matrix multiplying a given 3x3 matrix with each column of the array. Is there a good way to do this in a vectorized manner?

当前,我的问题是3xN,但将来可能需要考虑3xNxM(或更多).

Currently, my problem is 3xN, but I may need to consider 3xNxM (or more) in the future.

循环方法

U=numpy.rand( [3,24] )

R=numpy.eye(3) # placeholder

for i in xrange( U.shape[1]):
    U[:,i]=numpy.dot( R, U[:,i] )

推荐答案

使用np.einsum函数,甚至可以解决多维问题:

Using np.einsum function you can do it even for the multi dimension problem:

U = np.random.rand(3,24,5) 
R = np.eye(3,3)
result = np.einsum( "ijk,il", U,R )

这种表示法有些棘手:首先给出的字符串表示数组维数;因此对于U,指标ijk是每个维度的运行指标.它遵循爱因斯坦的求和约定,因此将对字符串中具有相同字母的索引求和.有关详细信息,请阅读 ScipyDocs .我敢肯定,在您的情况下,圆点会更快,因为开销较小,并且可能会使用一些blas例程,但是正如您所说的,您想扩展到更大的尺寸,这也许是解决方法.

The notation is a little tricky: the string you give first states the indeces of the dimensions of the arrays; so for U the indeces ijk are the running indeces for each dimension. It follows the einstein summation convention so indeces that have the same letter in the string will be summed over. For details read ScipyDocs. I'm sure in your case the dot is faster, because there is less overhead and it will probably use some blas routine, but as you stated that you want to expand to even more dimensions this might be the way to go.

这篇关于numpy:广播矩阵乘以整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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