问题
I am doing a simulation on a matrix (suppose a 5x5 matrix). One of the elements of this matrix is known (the back square in below; this location will not be always in center) and I want to start from that location and spirally visit the other elements (I have shown the orders in number). How I can define 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 sort the obtained matrix, but the results were not as what I want.
Any better solution?
回答1:
When 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 arbitrary position of the starting point we'll need to do something by hands
Let's exploit this fancy spiral function. To obtain the answer matrix A, make the bigger matrix M where the starting point is in the center. Note that relative order of the elements in A and in M is the same. All we need is to get A as a submatrix from M and fill it with 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's 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 thus takes O(N^2 logN) time comparing to direct O(N^2) implementation. But it is very short and works fast enough for matrices around 1000x1000.
来源:https://stackoverflow.com/questions/20259818/order-making-for-a-matrix-in-matlab