Multiply Two Arrays To Get Matrix
I have two numpy arrays #shape = (5,) a = np.array([1,2,3,4,5]) #shape = (3,) b = np.array([6,7,8]) I want to get a matrix from this arrays like this: #shape = (3,5) c = [ [1
Solution 1:
Try this:
>>> a*b.reshape(3,1)
array([[ 6, 12, 18, 24, 30],
[ 7, 14, 21, 28, 35],
[ 8, 16, 24, 32, 40]])
By reshaping b
, we are transforming it as follows:
>>> b.reshape(3,1)
array([[6],
[7],
[8]])
Since this is a 2d-array, whose second dimension is 1, numpy is able to multiply it by a
on the left by broadcastingb
. It will be as if the multiplication was actually
>>> np.array([1,2,3,4,5])*np.array([[6, 6, 6, 6, 6],
... [7, 7, 7, 7, 7],
... [8, 8, 8, 8, 8]])
array([[ 6, 12, 18, 24, 30],
[ 7, 14, 21, 28, 35],
[ 8, 16, 24, 32, 40]])
Post a Comment for "Multiply Two Arrays To Get Matrix"