Alex
Alex

Reputation: 15738

Return matrices of row and column indices

I am sure this question must be answered somewhere else but I can't seem to find the answer.

Given a matrix M, what is the most efficient/succinct way to return two matrices respectively containing the row and column indices of the elements of M.

E.g.

M = [1 5 ; NaN 2]

and I want

MRow = [1 1; 2 2]
MCol = [1 2; 1 2]

One way would be to do

[MRow, MCol] = find(ones(size(M)))
MRow = reshape(MRow, size(M))
MCol = reshape(MCol, size(M))

But this does not seem particular succinct nor efficient.

Upvotes: 1

Views: 37

Answers (2)

Matthew Gunn
Matthew Gunn

Reputation: 4529

Use meshgrid:

[mcol, mrow] = meshgrid(1:size(M,2),1:size(M,1))

Upvotes: 3

mikkola
mikkola

Reputation: 3476

This essentially amounts to building a regular grid over possible values of row and column indices. It can be achieved using meshgrid, which is more effective than using find as it avoids building the matrix of ones and trying to "find" a result that is essentially already known.

M = [1 5 ; NaN 2];

[nRows, nCols] = size(M);
[MCol, MRow] = meshgrid(1:nCols, 1:nRows);

Upvotes: 3

Related Questions