2

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]

1
  • 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. Commented Jan 9, 2014 at 17:11

1 Answer 1

4

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.]])
Sign up to request clarification or add additional context in comments.

Comments

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.