2

I'm new with Python and programming in general.

I want to create a function that multiplies two np.array of the same size and get their scalar value, for example:

matrix_1 = np.array([[1, 1], [0, 1], [1, 0]])
matrix_2 = np.array([[1, 2], [1, 1], [0, 0]])

I want to get 4 as output ((1 * 1) + (1 * 2) + (0 * 1) + (1 * 1) + (1 * 0) + (0 * 0))

Thanks!

accdias
  • 5,160
  • 3
  • 19
  • 31
Dor Cohen
  • 142
  • 5

4 Answers4

2
  1. Multiply two matrices element-wise
  2. Sum all the elements
multiplied_matrix = np.multiply(matrix_1,matrix_2)

sum_of_elements = np.sum(multiplied_matrix)

print(sum_of_elements) # 4

Or in one shot:

print(np.sum(np.multiply(matrix_1, matrix_2))) # 4
s.ouchene
  • 1,682
  • 13
  • 31
1

You can make use of np.multiply() to multiply the two arrays elementwise, then we call np.sum() on this matrix. So we thus can calculate the result with:

np.multiply(matrix_1, matrix_2).sum()

For your given sample matrix, we thus obtain:

>>> matrix_1 = np.array([[1, 1], [0, 1], [1, 0]])
>>> matrix_2 = np.array([[1, 2], [1, 1], [0, 0]])
>>> np.multiply(matrix_1, matrix_2)
array([[1, 2],
       [0, 1],
       [0, 0]])
>>> np.multiply(matrix_1, matrix_2).sum()
4
accdias
  • 5,160
  • 3
  • 19
  • 31
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

There are a couple of ways to do it (Frobenius inner product) using numpy, e.g.

np.sum(A * B)

np.dot(A.flatten(), B.flatten())

np.trace(np.dot(A, B.T))

np.einsum('ij,ij', A, B)
Andreas K.
  • 9,282
  • 3
  • 40
  • 45
0

One recommended way is using numpy.einsum, since it can be adapted to not only matrices but also multiway arrays (i.e., tensors).

  • Matrices of the same size

Take the matrices what you give as an example,

>>> import numpy as np
>>> matrix_1 = np.array([[1, 1], [0, 1], [1, 0]])
>>> matrix_2 = np.array([[1, 2], [1, 1], [0, 0]])

then, we have

>>> np.einsum('ij, ij ->', matrix_1, matrix_2)
4
  • Vectors of the same size

An example like this:

>>> vector_1 = np.array([1, 2, 3])
>>> vector_2 = np.array([2, 3, 4])
>>> np.einsum('i, i ->', vector_1, vector_2)
20
  • Tensors of the same size

Take three-way arrays (i.e., third-order tensors) as an example,

>>> tensor_1 = np.array([[[1, 2], [3, 4]], [[2, 3], [4, 5]], [[3, 4], [5, 6]]])
>>> print(tensor_1)
[[[1 2]
  [3 4]]

 [[2 3]
  [4 5]]

 [[3 4]
  [5 6]]]
>>> tensor_2 = np.array([[[2, 3], [4, 5]], [[3, 4], [5, 6]], [[6, 7], [8, 9]]])
>>> print(tensor_2)
[[[2 3]
  [4 5]]

 [[3 4]
  [5 6]]

 [[6 7]
  [8 9]]]

then, we have

>>> np.einsum('ijk, ijk ->', tensor_1, tensor_2)
248

For more usage about numpy.einsum, I recommend:

Understanding NumPy's einsum

Xinyu Chen
  • 11
  • 4