Search code examples
pythonnumpymatrixmatrix-multiplication

Matching Matrix sizes for matrix math


I am trying to perform matrix math using numpy. I have what I expect to be a 2x2x401 matrix that I am trying to add to an identity matrix using np.add(). In code, I have tried:

result = []
self.data = x #where x is a 2x2x401 np array
z_sqrt = np.identity(2)
for x in range(401):
    result.append(np.add(z_sqrt,self.data[:][:][x]))
    #if the above gives me errors because of how I'm assigning it, I'm not there yet

The error I get is:

ValueError: operands could not be broadcast together with shapes (2,2) (2,401)

Solution

  • Please try the following which might help,

    result = x + np.atleast_3d(np.identity(2))
    

    where x is your (2,2,401) array. The above should directly work on the whole array without using the for loop so you get result of shape (2,2,401) in a one-liner. Alternatively you can also try the below,

    result = x + (np.identity(2)[:,:,np.newaxis])