Answer the question
In order to leave comments, you need to log in
How to cut squares from a matrix?
I would like to cut out 3 by 3 squares from the matrix
[ [ 5, 3, 4, 6, 7, 8, 9, 1, 2 ],
[ 6, 7, 2, 1, 9, 5, 3, 4, 8 ],
[ 1, 9, 8, 3, 4, 2, 5, 6, 7 ],
[ 8, 5, 9, 7, 6, 1, 4, 2, 3 ],
[ 4, 2, 6, 8 , 5, 3, 7, 9, 1 ],
[ 7, 1, 3, 9, 2, 4, 8, 5, 6 ],
[ 9, 6, 1, 5, 3, 7, 2, 8, 4 ],
[ 2, 8, 7, 4, 1, 9, 6, 3, 5 ],
[ 3, 4, 5, 2, 8, 6, 1, 7, 9 ] ]
Then 1 square would be an array of
[ 5,3,4
6,7,2
1,9,8]
and so divide the entire matrix into 9 squares
Answer the question
In order to leave comments, you need to log in
In practice, it is better not to cut out the squares, but to transfer where you need the original matrix and the offset in it. Then there will be no extra memory allocations.
But if you need it, start a function that cuts out a square with the given coordinates and sizes (and in two nested loops over i and j from 0 to 2, run it from coordinates (3*i, 3*j).
The function starts an array of the desired size and for all i,j copies into cell [i,j] the value from the large matrix from cell [i+offset_x, j+offset_y].
In fact, this task can be done in very different ways. Destructive and not. Economical (array) and non-economical (jagged or two-dimensional array). And the author must concretize as he wants.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question