1

My goal is to shift the columns of an array B k positions to the left. Assume B is of the shape (n,n). Then of course, the columns from n to n-k have to replaced with some new entries. But this shouldn't be of importance here. What does work is the following:

for i in range(n):
   for j in range(n-k):
      B[i][j]  = B[i][j+k]

I wonder if there is a faster and simpler method. Any suggestions appreciated

2 Answers 2

1

If you were using your matrix in column-major order (i.e. using i as column index), much less copies would be needed

for j in range(n-k):
   B[i] = B[i+k]

in this case only the reference to the column is copied

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

Comments

0

You could use subscripts:

B = B[k:] + newValues

or, if you want to keep the array size and manipulate the original positions afterward:

B[:k] = B[k:2*k]

note that, in this last approach, you must have 2k <= n otherwise you won't have enough elements to fill the left side of the array

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.