Search code examples
matlabmathvectormatrixspiral

Convert a matrix to a vector using a spiral path


I have seen until now that when someone wants to read the elements of a matrix using a spiral one by one they always mean starting outwards and slowly moving to the center using an MxM matrix. How would we do the opposite, start from a random point inside the matrix and using a "spiraling" path to read all the elements.

I am doing the tests using Matlab.

Example.

mat=
  1 2 3
  4 5 6
  7 8 9 

If lets say we were to start from mat(3,1) spiraling clockwise then we would have

vec=
  7, 8, 4, 5, 6, 9, 1, 2, 3

and if we started from mat(2,2) then

vec=
5, 6, 9, 8, 7, 4, 1, 2, 3

Solution

  • One possible approach:

    mat = [1 2 3; 4 5 6; 7 8 9];
    M = length(mat); % Assuming mat is always MxM
    
    r = 3;
    c = 1;
    
    temp = spiral(2 * M - 1);
    temp = temp(M - r + 1:end - r + 1, M - c + 1:end - c + 1);
    [~, idx] = sort(temp(:));
    vec = mat(idx).'
    

    Result running with r = 3 and c = 1

    vec =
    
         7     8     4     5     6     9     1     2     3
    

    Result running with r = 2 and c = 2

    vec =
    
         5     6     9     8     7     4     1     2     3