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.

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
Ned Taylor
  • 11
  • 3

1 Answers1

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.

Green绿色
  • 1,620
  • 1
  • 16
  • 43
  • 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 – Ned Taylor Feb 17 '22 at 18:51
  • Normally, @Michael Szczensny's answer should work for you: `a[rows[:,None], cols] += b`. At least, it does on your example. – Green绿色 Feb 18 '22 at 01:53