1

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!

1
  • ind2sub and meshgrid are closely related Commented Oct 9, 2013 at 19:14

2 Answers 2

2
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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.