1

Let's say I have an array A[i,j] and I want to compute a new quantity B[i,j] by doing something like:

for i in arange(1, n):
    B[i,j+1] = a*A[i-1,j] + b*A[i,j]+ c*A[i+1,j]

What numpy functionality can I use to turn this into a pure array operation?

I was thinking of np.cumprod but it's unclear how to incorporate the coefficients into the calculation.

A.shape will be (n+1, j).

0

2 Answers 2

2

Define A_left = A[:-2, :], A_middle = A[1:-1, :] and A_right = A[2:, :]

Then B = a*A_left + b*A_middle + c*A_right

Sign up to request clarification or add additional context in comments.

4 Comments

I think the assignment part would be B[1:-1] = ...
Yes, but actually the question is kind of ill-posed since when i is n-1, OP's last line raises an IndexError.
It's because OP most probably has A as n+1 as the number of rows to account for A[i+1,j].
Possible, but not sure :) hence "kinf of ill-posed". Good point, I've just asked for A.shape in a comment.
1

If you don't mind a bit of signal processing, you could have a generic solution (generic in the sense where you could assign more elements alongside a, b and c for scaling element from A) using signal.convolve2d.

This would be similar to this other solution where the theory of convolution as related to such cases is dealt with in a bit more detailed manner. The implementation would look like this -

from scipy import signal

B = np.zeros_like(A)

kernel = np.array([a,b,c])[::-1,None]
B[1:-1]  = signal.convolve2d(A, kernel, boundary='symm', mode='valid')

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.