Reputation: 3377
a = np.asarray([1,2,3])
b = np.asarray([2,3,4,5])
a.shape
(3,)
b.shape
(4,)
I want a 3 by 4 matrix that's the product of a and b
1
2 * 2 3 4 5
3
np.dot(a, b.transpose())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: objects are not aligned
dot product is only equivalent to matrix multiplication when the array is 2d, so np.dot doesn't work.
Upvotes: 3
Views: 2230
Reputation: 73
the following code does as demanded basically you did a mistake while reshaping the arrays , you should reshape them so as to ensure matrix multiplication property is satisfied.
a = np.asarray([1,2,3])
b = np.asarray([2,3,4,5])
a.reshape(3,1)
Upvotes: 0
Reputation: 281152
This is np.outer(a, b)
:
In [2]: np.outer([1, 2, 3], [2, 3, 4, 5])
Out[2]:
array([[ 2, 3, 4, 5],
[ 4, 6, 8, 10],
[ 6, 9, 12, 15]])
Upvotes: 7
Reputation: 231385
No need to use the matrix
subtype. Regular array
can be expanded to 2d (and transposed if need).
In [2]: a=np.array([1,2,3])
In [3]: b=np.array([2,3,4,5])
In [4]: a[:,None]
Out[4]:
array([[1],
[2],
[3]])
In [5]: a[:,None]*b # outer product via broadcasting
Out[5]:
array([[ 2, 3, 4, 5],
[ 4, 6, 8, 10],
[ 6, 9, 12, 15]])
Other ways of making that column array
In [6]: np.array([[1,2,3]]).T
Out[6]:
array([[1],
[2],
[3]])
In [7]: np.array([[1],[2],[3]])
Out[7]:
array([[1],
[2],
[3]])
In [9]: np.atleast_2d([1,2,3]).T
Out[9]:
array([[1],
[2],
[3]])
Upvotes: 4
Reputation: 1676
Instead of asarray
, use asmatrix
.
import numpy as np
a = np.asmatrix([1,2,3])
b = np.asmatrix([2,3,4,5])
a.shape #(1, 3)
b.shape #(1, 4)
np.dot(a.transpose(),b)
Results in:
matrix([[ 2, 3, 4, 5],
[ 4, 6, 8, 10],
[ 6, 9, 12, 15]])
Upvotes: 0