I have 9x9 matrix in numpy. I need fast method to change it into sudoku-like 9x9 array with cubes (also I need method to reverse this operation). I attach conceptual drawing.
Asked
Active
Viewed 183 times
1
-
1Welcome to StackOverflow! That's an interesting question. What did you try and/or research? Why didn't that work for you? – Jondiedoop Mar 24 '19 at 08:30
-
Hi! The original form of matrix is easier for me to work with (doing checks etc.) but I need sudoku-like representation for convolutional neural network – minami1120 Mar 24 '19 at 08:49
-
Did the posted solution work for you? – Divakar Mar 24 '19 at 13:57
1 Answers
0
Reshape, permute axes and reshape -
In [43]: a
Out[43]:
array([[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 6, 7, 8]])
In [44]: a.reshape(3,3,3,3).swapaxes(1,2).reshape(9,9)
Out[44]:
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8]])
On a generic shaped array, it would be -
m,n = a.shape
H,W = (3,3) # block size on sudoku
out = a.reshape(m//H,H,n//W,W).swapaxes(1,2).reshape(m,n)
More info on intuition behind nd-to-nd array transformation
.
If you want to start from scratch, use kron
on a ranged-array -
In [65]: np.kron(np.ones((3,3),dtype=int),np.arange(9).reshape(3,3))
Out[65]:
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8]])

Divakar
- 218,885
- 19
- 262
- 358