Search code examples
matlabmultidimensional-arraycell

construct cell array of ordered pairs from matrices


I want to create a cell array of ordered pairs from the following two matrices...

i.e.

[X,Y] = meshgrid(1:10,1:10)

X =

 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10
 1     2     3     4     5     6     7     8     9    10

Y =

 1     1     1     1     1     1     1     1     1     1
 2     2     2     2     2     2     2     2     2     2
 3     3     3     3     3     3     3     3     3     3
 4     4     4     4     4     4     4     4     4     4
 5     5     5     5     5     5     5     5     5     5
 6     6     6     6     6     6     6     6     6     6
 7     7     7     7     7     7     7     7     7     7
 8     8     8     8     8     8     8     8     8     8
 9     9     9     9     9     9     9     9     9     9
10    10    10    10    10    10    10    10    10    10

...where the (what I assume to be 1x2x10x10) cell array Z is a cell array where all of the entries in X and Y are x and y coordinates, with each individual pair of coordinates being an element of Z:

Z = { (1,1)  (2,1)  (3,1)  ... (10,1);
  (1,2)  (2,2)  (3,2)  ... (10,2);
  ...     ...    ...   ...  ...;
  (1,10) (2,10) (3,10) ... (10,10) }

How would I go about doing this?


Solution

  • Z = squeeze(num2cell(permute(cat(3,X,Y),[3,1,2]),1));
    

    Steps:

    1. Concatenate X and Y along the third dimension:

      Z = cat(3,X,Y)
      
    2. Permute the resulting array to have coordinate pairs along first dimension:

      Z = permute(Z,[3,1,2])
      
    3. Convert to cell array:

      Z = num2cell(Z)
      
    4. Remove unnecessary singleton dimensions from cell array:

      Z = squeeze(Z)
      

    The resulting cell array contains the coordinate pairs as 2x1 column vectors on the form

    [x-coordinate; y-coordinate]