Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternating values in a numpy matrix

I'm trying to represent a checkerboard using a numpy matrix comprised of 1s and 0s. It should be able to have dimensions of odd length. Something like

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

board = np.resize([0, 1], (3, 5)) works but only because the dimensions are odd, and they could also potentially be even. Is there a fast way to accomplish this?

like image 826
FutureShocked Avatar asked Feb 27 '26 06:02

FutureShocked


1 Answers

Use parity of indices:

n = 4
p = 5
np.array([[(i+j)%2 for i in range(n)] for j in range(p)])
like image 119
Julien Avatar answered Feb 28 '26 19:02

Julien