Making order for matrix in matlab

I am doing a simulation on a matrix (suppose a 5x5 matrix). One of the elements of this matrix is ​​known (the back square at the bottom, this place will not always be in the center), and I want to start from this place and alternately visit other elements (I showed the numbers in order). How can I determine this order in a large matrix (e.g. 1000x1000)? Because I cannot do it manually, and I am looking for a more heuristic way.

I used bwdist in matlab and then sorted the resulting matrix, but the results were not what I want.

The best solution?

enter image description here

+3
source share
1 answer

When the element is in the center, just use the spiral command:

 >> spiral(5) ans = 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 

For an arbitrary position of the starting point, we will need to do something with our hands

We take advantage of this fantastic spiral function. To get the answer matrix A , make a large matrix M , where the starting point is in the center. Note that the relative order of elements in A and in M same. We only need to get A as a submatrix from M and fill it with a continuous array of elements in the same order:

 function A = spiral_generic(n, P) % Makes NxN matrix filled up spirally starting with point P r = max([P - 1, n - P]); % Radius of the bigger matrix M = spiral(2 * r + 1); % Bigger matrix itself C = r + 1 - (P - 1); % Top-left corner of A in M A = M(C(1):C(1)+n-1, C(2):C(2)+n-1); % Get the submatrix [~, order] = sort(A(:)); % Get elements' order A(order) = 1:n^2; % Fill with continous values end 

And here is how it works:

 >> spiral_generic(5, [3 2]) ans = 17 18 19 20 21 7 8 9 10 22 6 1 2 11 23 5 4 3 12 24 16 15 14 13 25 >> spiral_generic(6, [2 5]) ans = 36 25 16 7 8 9 35 24 15 6 1 2 34 23 14 5 4 3 33 22 13 12 11 10 32 21 20 19 18 17 31 30 29 28 27 26 

This is not the fastest solution, since it requires sorting and, therefore, takes O(N^2 logN) compared to the direct O(N^2) implementation. But it is very short and works fast enough for matrices of about 1000x1000.

+3
source

Source: https://habr.com/ru/post/984730/


All Articles