简体   繁体   中英

Fastest way to create a numpy matrix with multiples of a vector

Let x,y be two numpy arrays of N elements. I want to create a numpy matrix whose columns are scaled-shifted versions of x. For instance, say

m=[0.2, 0.4, 1.2]

Then I want the matrix

X = [0.2x+y, 0.4x+y, 1.2x+y]

What's the fastest (easiest as well, easiest being second priority) way to do this.

Currently I am doing something like this.

ListVec = [m[i]*x+y for i in numpy.arange(len(m))]
X = numpy.array(ListVec).T
import numpy as np 
m = np.array([0.2, 0.4, 1.2])
x = 5
y = 3
X = m*x+y

This is called broadcasting in numpy (both easy and fast ;))

use Einstein Summation for case when X and Y are arrays

In [70]: Y
Out[76]: array([5, 6, 7, 8, 9])

In [71]: X
Out[71]: array([0, 1, 2, 3, 4])

In [72]: m
Out[72]: [0.2, 0.4, 1.2]

In [73]: np.einsum('i,j', X, m)
Out[73]: 
array([[0. , 0. , 0. ],
       [0.2, 0.4, 1.2],
       [0.4, 0.8, 2.4],
       [0.6, 1.2, 3.6],
       [0.8, 1.6, 4.8]])

In [74]: Y[...,np.newaxis] + np.einsum('i,j', X, m)
Out[74]: 
array([[ 5. ,  5. ,  5. ],
       [ 6.2,  6.4,  7.2],
       [ 7.4,  7.8,  9.4],
       [ 8.6,  9.2, 11.6],
       [ 9.8, 10.6, 13.8]])

It would have helped if you'd given example x and y as well as m , but:

In [435]: x,y = np.array([1,2,3,4]), np.array([.1,.2,.3,.4])
In [436]: m = [.2,.4,1.2]

So the result is (3,N):

In [437]: np.array([i*x+y for i in m])
Out[437]: 
array([[0.3, 0.6, 0.9, 1.2],
       [0.5, 1. , 1.5, 2. ],
       [1.3, 2.6, 3.9, 5.2]])

broadcasting with m :

In [438]: np.array(m)[:,None]*x + y
Out[438]: 
array([[0.3, 0.6, 0.9, 1.2],
       [0.5, 1. , 1.5, 2. ],
       [1.3, 2.6, 3.9, 5.2]])

oops, I missed your transpose,

In [440]: np.array(m)*x[:,None] + y[:,None]
Out[440]: 
array([[0.3, 0.5, 1.3],
       [0.6, 1. , 2.6],
       [0.9, 1.5, 3.9],
       [1.2, 2. , 5.2]])

I'd go ahead a apply the transpose to [438]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM