3

I am new to python. How can I do dot product of 3 arrays in python numpy. I have three matrices

[1 2 3]
[4 5 6]
[-1 -2 -3]

I want to do (1x4x(-1)) + (2x5x(-2)) + (3x6x(-3)) = -4-20-36 = -50

  • 1
    output is not -50, this is -78, -4-20-54=-78 – just a stranger Oct 11 '20 at 19:33
  • This is usually not called a dot product but rather a **scalar triple product**: [Wikipedia](https://en.wikipedia.org/wiki/Triple_product); [Mathinsight.org](https://mathinsight.org/scalar_triple_product). – Stef Oct 26 '21 at 16:00

2 Answers2

3

Assuming your numpy arrays are a, b, and c, respectively:

>>> (a * b).dot(c)
-78
Alexander
  • 105,104
  • 32
  • 201
  • 196
0
In [123]: a=np.array([1, 2, 3])
     ...: b=np.array([4, 5, 6])
     ...: c=np.array([-1, -2, -3])

Combine them into one array:

In [124]: arr = np.vstack((a,b,c))
In [125]: arr
Out[125]: 
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [-1, -2, -3]])

Taking product down the columns, followed by a sum.

In [127]: np.prod(arr, axis=0)
Out[127]: array([ -4, -20, -54])
In [128]: np.sum(np.prod(arr, axis=0))
Out[128]: -78

or

np.sum(a*b*c)

Another approach

np.einsum('i,i,i', a, b, c)

Again this is the sum of all products.

hpaulj
  • 221,503
  • 14
  • 230
  • 353