2

Is there a fast way in numpy to add array A to array B at a specified location?

For instance, if

B = [
    [0, 1, 2],
    [2, 3, 4],
    [5, 6, 7]
]

and

A = [
    [2, 2],
    [2, 2]
]

and I want to add A to B starting from point (0, 0) to get

C = [
    [2, 3, 2],
    [4, 5, 4],
    [5, 6, 7],
]

Of course I can do that via extending the array A to match the shape of B and then using numpy.roll, but it seems unnecessarily slow if the size of A is much much smaller then size of B.

EDIT:

potentially with wrapping around - ie such that bottom row of A is added to the top row of B and top row of A is added to the bottom row of B

1 Answer 1

1

To modify B in place

B[:2,:2] += A

otherwise

C = B.copy()
C[:2,:2] += A
Sign up to request clarification or add additional context in comments.

1 Comment

Great! is there any easy way to add a wrap-around though? B[-2:2, -2:2] does not seem to do anything meaningful =(

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.