1

in the example below, there is a 3d matrix of size (4, 3, 3). how to calculate pinv of each of 4 of those 3*3 matrices without a loop in numpy?

dt = np.dtype(np.float32)

a=[[[12,3,1],
   [2,4,1],
   [2,4,2],],
   [[12,3,3],
   [2,4,4],
   [2,4,5],],
   [[12,3,6],
   [2,4,5],
   [2,4,4],],
   [[12,3,3],
   [2,4,5],
   [2,4,6]]]

a=np.asarray(a,dtype=dt)
print(a.shape)

apinv=np.zeros((4,3,3))
print(np.linalg.pinv(a[0,:,:]).shape)

for i in range(4):
   apinv[i,:,:]=np.linalg.pinv(a[i,:,:])

Please note that linalg.inv broadcasts through the matrix as it is described here:

print(np.linalg.inv(a).shape)

But it doesn't work the same way for pinv.

PickleRick
  • 419
  • 1
  • 5
  • 13

1 Answers1

1

One solution would be using map and lambda functions:

apinv = map(lambda n: np.linalg.pinv(n), a)
apinv = np.asarray(apinv,dtype=dt)
Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59