-2

I have the following code where I used two for loops to iterate through and array and copy elements to another at an offset position, how could this be done without for loops for faster computation?

for i in range (data1.shape[0]):
    for j in range (data1.shape[1]):
        try:
            translated[i+x_cord][j+y_cord]=data1[i][j]

        except:
            pass

Here, I'm just doing image translation.

zvone
  • 18,045
  • 3
  • 49
  • 77
Shivam Thakur
  • 63
  • 1
  • 11
  • 1
    Yes, use slices. – Julien Mar 25 '19 at 23:11
  • Do you know how to index (with slices) the target zone in `translated`? Why does your loop code use a `try/except`? Do you expect that some of the assignments will not work? will be out of bounds? Can you tell us the `shape` of `translated`, and it relates to the shape of `data1` and the offset? – hpaulj Mar 25 '19 at 23:25

1 Answers1

0

This will do:

translated[x_cord:min(x_cord+data1.shape[0],translated.shape[0]), y_cord:min(y_cord+data1.shape[1],translated.shape[1])] = data1[:min(data1.shape[0],translated.shape[0]-x_cord), :min(data1.shape[1],translated.shape[1]-y_cord)]    

The min stuff is to ensure you are not going out of bounds (analog of your try, except), the rest is basic slicing...

Julien
  • 13,986
  • 5
  • 29
  • 53