Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am having problem to add a subarray to an existing 2D array. I am actually new to numpy and python and coming from MATLAB this was something trivial to do. Note that usually a is a big matrix in my problems.

import numpy as np

a = np.array(arange(16)).reshape(4,4) # The initial array
b = np.array(arange(4)).reshape(2,2) # The subarray to add to the initial array
ind = [0,3] # The rows and columns to add the 2x2 subarray 

a[ind][:,ind] += b #Doesn't work although does not give an error

I saw looking around that the following can work

a[:4:3,:4:3] += b

but how can I define ind beforehand? In addition how to define ind if it consists of more than two numbers that cannot be expressed with a stride? for example ind = [1, 15, 34, 67]

share|improve this question
1  
Just to explain why a[ind][:,ind] += b doesn't work, it's because a[ind] (where ind is a sequence of coordinates) makes a copy. Therefore, it does work, but the += is applied to the copy, which is not saved. a winds up being unchanged. Basically, it's because you have use "fancy" indexing twice. @DSM's answer combines it into one "fancy" indexing expression, so += works as expected. Another way to write it is a[ind[:,None], ind[None,:]] += b, but that requires ind to be a numpy array instead of a list. –  Joe Kington yesterday
add comment

1 Answer

up vote 4 down vote accepted

One way to handle the general case would be to use np.ix_:

>>> a = np.zeros((4,4))
>>> b = np.arange(4).reshape(2,2)+1
>>> ind = [0,3]
>>> np.ix_(ind, ind)
(array([[0],
       [3]]), array([[0, 3]]))
>>> a[np.ix_(ind, ind)] += b
>>> a
array([[ 1.,  0.,  0.,  2.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 3.,  0.,  0.,  4.]])
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.