1

So suppose i have two numpy ndarrays whose elements are matrices. I need element-wise multiplication for these two arrays, however, there should be matrix multiplication between the two matrix elements. Of course i would be able to implement this with for loops but i was looking to solve this problem without using an explicit for loop. How do i implement this?

EDIT: This for-loop does what I want to do. I'm on python 2.7

n = np.arange(8).reshape(2,2,1,2)
l = np.arange(1,9).reshape(2,2,2,1)
k = np.zeros((2,2))
for i in range(len(n)):
    for j in range(len(n[i])):
        k[i][j] =  np.asscalar(n[i][j].dot(l[i][j]))
print k

2 Answers2

3

Assuming your arrays of matrices are given as n+2 dimensional arrays A and B. What you want to achieve is as simple as C = A@B

Example

outer_dims = 2,3,4
inner_dims = 4,5,6

A = np.random.randint(0,10,(*outer_dims, *inner_dims[:2]))
B = np.random.randint(0,10,(*outer_dims, *inner_dims[1:]))

C = A@B

# check
for I in np.ndindex(outer_dims):
    assert (C[I] == A[I]@B[I]).all()

UPDATE: Py2 version; thanks @ hpaulj, Divakar

A = np.random.randint(0,10, outer_dims + inner_dims[:2])
B = np.random.randint(0,10, outer_dims + inner_dims[1:])

C = np.matmul(A,B)

# check
for I in np.ndindex(outer_dims):
    assert (C[I] == np.matmul(A[I],B[I])).all()
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
0

If I understand correctly, this might work:

import numpy as np

a = np.array([[1,1],[1,0]])
b = np.array([[3,4],[5,4]])

x = np.array([[a,b],[b,a]])
y = np.array([[a,a],[b,b]])

result = np.array([_x @ _y for _x, _y in zip(x,y)])
Itamar Mushkin
  • 2,803
  • 2
  • 16
  • 32