terez tukan
terez tukan

Reputation: 13

matrix to cell matrix of indices

Given a matrix of n dimensions, how can I convert it to a matrix of indices as seen below:

click here

Upvotes: 0

Views: 288

Answers (3)

patrik
patrik

Reputation: 4558

The function ind2sub should work. Another option is to calculate it by hand. This is easy. Note the stucture of the matrix. It is denoted by linear indexing distributed columnwise. This mean that the indices can be calculated as:

idxRow = mod(idx-1,nRows)+1;
idxCol = ceil(idx./nColumns);

This is more or less what is done in ind2sub except that function cleverly solves the problem for an N-dimensional matrix. And also have some error handling.

Upvotes: 1

NKN
NKN

Reputation: 6424

As mentioned by MATLAB documents, you can use ind2sub function:

IND = [3 4 5 6]
s = [3,3];
[I,J] = ind2sub(s,IND)

I =
     3     1     2     3

J =
     1     2     2     2

Upvotes: 3

Adriaan
Adriaan

Reputation: 18177

n = 3;
[X,Y] = meshgrid(1:n);
C = cell(n,n);
for ii = 1:n
    for jj = 1:n
        C{ii,jj} = [X(ii,jj) Y(ii,jj)];
    end
end

Note that the X and Y matrices are probably what you are looking for, since they are matrices. To also include the cell of indices I had to use a nested loop, but there's probably a vectorised way to do that as well.

X =
     1     2     3
     1     2     3
     1     2     3
Y =
     1     1     1
     2     2     2
     3     3     3
C = 
    [1x2 double]    [1x2 double]    [1x2 double]
    [1x2 double]    [1x2 double]    [1x2 double]
    [1x2 double]    [1x2 double]    [1x2 double]

where each [1x2 double] is the requested combination of indices.

Upvotes: 0

Related Questions