socoho
socoho

Reputation: 339

Create matrix in Matlab enumerating coordinates

Is there an efficient way (e.g., without using for loops manually) to create a matrix in Matlab that enumerates the 2-D coordinates of a matrix of a given size?

For example, if I'm given an m x n matrix, I want the resulting mn x 2 matrix to be as follows:

1  1
1  2
1  3
...
1  n
2  1
2  2
...
m  1
m  2
...
m  n

Thanks in advance!

Upvotes: 1

Views: 161

Answers (2)

chappjc
chappjc

Reputation: 30579

Robert P. has a correct (and elegant) answer with a nifty use of kron, but just for fun here's the alternative with ndgrid,

>> mat=zeros(5,2);
>> [nn,mm] = ndgrid(1:size(mat,2),1:size(mat,1))
>> vec = [mm(:) nn(:)]
vec =
     1     1
     1     2
     2     1
     2     2
     3     1
     3     2
     4     1
     4     2
     5     1
     5     2

Upvotes: 1

Stewie Griffin
Stewie Griffin

Reputation: 14939

mat = [1 2;3 4;5 6;7 8;9 10];
[m,n] = size(mat);
vec = [kron(1:m,ones(1,n)); kron(ones(1,m),1:n)]'
   1   1
   1   2
   2   1
   2   2
   3   1
   3   2
   4   1
   4   2
   5   1
   5   2

Upvotes: 2

Related Questions