Reputation:
This question is a follow-up of a previous post of mine:
Multiply each column of a numpy array with each value of another array.
Suppose i have the following arrays:
In [252]: k
Out[252]:
array([[200, 800, 400, 1600],
[400, 1000, 800, 2000],
[600, 1200, 1200,2400]])
In [271]: f = np.array([[100,50],[200,100],[300,200]])
In [272]: f
Out[272]:
array([[100, 50],
[200, 100],
[300, 200]])
How can i subtract f from k to obtain the following?
In [252]: g
Out[252]:
array([[100, 750, 300, 1550],
[200, 900, 600, 1900],
[300, 1000, 900,2200]])
Ideally, i would like to make the subtraction in as fewer steps as possible and in concert with the solution provided in my other post, but any solution welcome.
Upvotes: 2
Views: 3427
Reputation: 42748
You can reshape k
, to fit f
in two dimensions, and use broadcasting:
>>> g = (k.reshape(f.shape[0], -1, f.shape[1]) - f[:, None, :]).reshape(k.shape)
array([[ 100, 750, 300, 1550],
[ 200, 900, 600, 1900],
[ 300, 1000, 900, 2200]])
Upvotes: 0
Reputation: 77404
You can use np.tile
, like this:
In [1]: k - np.tile(f, (1, 2))
Out[1]:
array([[ 100, 750, 300, 1550],
[ 200, 900, 600, 1900],
[ 300, 1000, 900, 2200]])
Also, if you happen to know for sure that each dimension of f
evenly divides the corresponding dimension of k
(which I assume you must, for your desired subtraction to make sense), then you could generalize it slightly:
In [2]: k - np.tile(f, np.array(k.shape) // np.array(f.shape))
Out[2]:
array([[ 100, 750, 300, 1550],
[ 200, 900, 600, 1900],
[ 300, 1000, 900, 2200]])
Upvotes: 1