1

I have a numpy zero matrix and size = (4, 8)

x = [[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],]

In addition, I have three different matrixes.

a = [[1, 1, 1 , 1, 1, 1, 1, 1],
     [1, 1, 1 , 1, 1, 1, 1, 1],
     [1, 1, 1 , 1, 1, 1, 1, 1],
     [1, 1, 1 , 1, 1, 1, 1, 1],]

b = [[2, 2, 2 , 2, 2, 2, 2, 2],
     [2, 2, 2 , 2, 2, 2, 2, 2],
     [2, 2, 2 , 2, 2, 2, 2, 2],
     [2, 2, 2 , 2, 2, 2, 2, 2],] 

c = [[3, 3, 3 , 3, 3, 3, 3, 3],
     [3, 3, 3 , 3, 3, 3, 3, 3],
     [3, 3, 3 , 3, 3, 3, 3, 3],
     [3, 3, 3 , 3, 3, 3, 3, 3],]

I want to get the following results

output = [[1, 2, 1, 2, 1, 2, 1, 2],
          [2, 3, 2, 3, 2, 3, 2, 3],
          [1, 2, 1, 2, 1, 2, 1, 2],
          [2, 3, 2, 3, 2, 3, 2, 3],]

The value of matrix a appears in (row 0, row 2) and (column 0, column 2, column 4, column 6)

The value of matrix b appears in row 0, row 1, row 2, row 3, but in the row 0 and row 2 the value 2 appears in the column 1, column 3, column 5, column 7, next in the row 1 and row 3 the value 2 appears in the column 0, column 2, column 4, column 6

The value of matrix c appears in (row 1, row 3) and (column 1, column 3, column 5, column 7)

import numpy as np
h, w = x.shape
output = np.zeros((h, w))

for i in range(h):
    for j in range(w):
        if (i % 2) == 0 and (j % 2) == 0:
            output[i, j] = a[i, j]
        elif (i % 2) == 1 and (j % 2) == 1:
            output[i, j] = c[i, j]
        else:
            output[i, j] = b[i, j]
print(output)
'''  
output = [[1. 2. 1. 2. 1. 2. 1. 2.]
          [2. 3. 2. 3. 2. 3. 2. 3.]
          [1. 2. 1. 2. 1. 2. 1. 2.]
          [2. 3. 2. 3. 2. 3. 2. 3.]]
'''

I want to try not to use the for loop, can I solve it with numpy?

vincentlai
  • 379
  • 5
  • 18

2 Answers2

4

You can use np.choose:

y,x = np.ogrid[:4,:8]
np.choose((y&1)+(x&1),[a,b,c])
# array([[1, 2, 1, 2, 1, 2, 1, 2],
#        [2, 3, 2, 3, 2, 3, 2, 3],
#        [1, 2, 1, 2, 1, 2, 1, 2],
#        [2, 3, 2, 3, 2, 3, 2, 3]])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
1

You need to select indexes where rows & columns are odd / even respectively. It has been explained here

import numpy as np
b = np.ones((4,8))*2

# update places where both row & column are even
b[::2,::2] -= 1
# update places where both row & column are odd
b[1::2,1::2] += 1

enter image description here

eMad
  • 998
  • 3
  • 13
  • 31