0

I have 2 numpy arrays

[a] = [[1] [2] [3]]
[b] = [[4] [5] [6]]

I want to convert matlab line to python

A = a*b';

How I will do this in python and what ' signifies in matlab?

2

2 Answers 2

3

use numpy.dot:

In [7]: a=np.array([1,2,3])

In [8]: b=np.array([4,5,6,])

In [9]: a.dot(b)
Out[9]: 32

if you want the result still be a matrix, use numpy.matrix:

In [239]: ma=matrix([1,2,3])

In [240]: ma
Out[240]: matrix([[1, 2, 3]])

In [241]: mb=matrix([4,5,6])

In [242]: mb.T
Out[242]: 
matrix([[4],
        [5],
        [6]])

In [243]: ma*mb.T
Out[243]: matrix([[32]])

update:

If your arrays are 2D arrays, which are of shape (m, n) when you print a.shape, you should transpose the second array using .T, otherwise you get ValueError: objects are not aligned:

In [30]: a
Out[30]: array([[1, 2, 3]])
In [31]: b
Out[31]: array([[4, 5, 6]])
In [32]: a.dot(b.T)
Out[32]: array([[32]])
In [33]: a.dot(b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-9a1f5761fa9d> in <module>()
----> 1 a.dot(b)
ValueError: objects are not aligned
Sign up to request clarification or add additional context in comments.

Comments

1

you need transpose the first array:

import numpy as np
a = np.array([[1], [2], [3]])
b = np.array([[4], [5], [6]])
np.dot(a.T, b)

or the second array:

np.dot(a, b.T)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.