Reputation: 39
I have question about matrix addition. I have a matrix A = np.ones([10,10]) and a matrix B = np.array([[2,2,2],[2,2,2],[2,2,2]]). Now I want to add matrix B into A but on specific positions, rows 2,6,7 and columns 2,6,7.
How should I do to get the following matrix:
[[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,3,1,1,1,3,3,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,3,1,1,1,3,3,1,1],
[1,1,3,1,1,1,3,3,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1]]
I'm more used to Matlab and there, it would look something like this: A((3,7,8),(3,7,8)) = A((3,7,8),(3,7,8)) + B. I tried something similar in Python but the dimensions didnt match.
Upvotes: 1
Views: 470
Reputation: 1408
Here is one way to do it:
Multidimensional indexing in Python requires you to explicitly index every cell. So you need to first create the indexing, and then use it as follows:
ind = np.array([[2,6,7]]) # Notice the 2D array
rows = np.broadcast_to(ind.transpose(), (3,3))
cols = np.broadcast_to(ind, (3,3))
A[rows, cols]+=B # A cell from rows matrix and a corresponding cell in cols matrix together form one cell index.
Output:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
[1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
Do read: https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html
For some reason, while the following does pick out the right matrix from A
, assignment to it does not work:
ind_1 = np.array([2,6,7])
A[ind_1,:][:, ind_1] = B # No error, but assignment does not take place
Upvotes: 2