1

Suppose I have a 6x6 matrix I want to add into a 9v9 matrix, but I also want to add it at a specified location and not necessarily in a 6x6 block.

The below code summarizes what I want to accomplish, the only difference is that I want to use variables instead of the rows 0:6 and 3:9.

import numpy as np

a = np.zeros((9,9)) 
b = np.ones((6,6))

a[0:6,3:9] += b  #Inserts the 6x6 ones matrix into the top right corner of the 9x9 zeros

Now using variables:

rows = np.array([0,1,2,3,4,5])
cols = np.array([3,4,5,6,7,8])

a[rows,3:9] += b #This works fine
a[0:6,cols] += b #This also works fine
a[rows,cols += b #But this gives me the following error: ValueError: shape mismatch: value array of shape (6,6) could not be broadcast to indexing result of shape (6,)

I have spent hours reading through forums and trying different solutions but nothing has ever worked. The reason I need to use variables is because these are input by the user and could be any combination of rows and columns. This notation worked perfectly in MatLab, where I could add b into a with any combination of rows and columns.

1
  • a[rows[:,None], cols] += b, to index the rows with rows. 1-D arrays are different from matrices in MatLab. Commented Feb 17, 2022 at 9:36

1 Answer 1

1

Explanation:

rows = np.array([0,1,2,3,4,5])
cols = np.array([3,4,5,6,7,8])

a[rows,cols] += b

You could translate the last line to the following code:

for x, y, z in zip(rows, cols, b):
  a[x, y] = z

That means: rows contains the x-coordinate, cols the y-coordinate of the field you want to manipulate. Both arrays contain 6 values, so you effectively manipulate 6 values, and b must thus also contain exactly 6 values. But your b contains 6x6 values. Therefore this is a "shape mismatch". This site should contain all you need about indexing of np.arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. Although I couldn't get the above solution to work. I read through the link and was able to get what I wanted with the np.ix_() function
Normally, @Michael Szczensny's answer should work for you: a[rows[:,None], cols] += b. At least, it does on your example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.