2

in matlab/ GNU Octave( which i am actually using ), I use this method to copy particular elements of a 2D array to another 2D array:

B(2:6, 2:6) = A

where

size(A) = (5, 5)

My question is, "How can this be achieved in python using numpy?" currently, for example, I am using the following nested loop in python:

>>> import numpy as np
>>> a = np.int32(np.random.rand(5,5)*10)
>>> b = np.zeros((6,6), dtype = np.int32)

>>> print a
[[6 7 5 1 3]
 [3 9 7 2 0]
 [9 3 7 6 7]
 [9 8 2 0 8]
 [8 7 7 9 9]]
>>> print b
[[0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]]

>>> for i in range(1,6):
        for j in range(1,6):
            b[i][j] = a[i-1][j-1]
>>> print b
[[0, 0, 0, 0, 0, 0],
 [0, 6, 7, 5, 1, 3],
 [0, 3, 9, 7, 2, 0],
 [0, 9, 3, 7, 6, 7],
 [0, 9, 8, 2, 0, 8],
 [0, 8, 7, 7, 9, 9]]

Is there a better way to do this?

1 Answer 1

5

It's almost the same as the MATLAB:

b[1:6, 1:6] = a

The only thing is that Python uses 0-based indexing so the second element is 1 instead of 2.

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

2 Comments

Oh, thanks. That's it! I was trying it as b[1:6][1:6]. Now i feel so silly asking this question.........
google 'numpy for matlab users' theres a great reference guide in the numpy docs

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.