# How to construct a matrix values by its row or column indexes?

42 views (last 30 days)
Antonio Trujillo-Ortiz on 9 Jul 2013
Hi all,
I need your help on this. Suppose we have a 4x3 matrix and we need to construct a metrix with its row and column indexes as follows,
R = 1 1 1; 2 2 2; 3 3 3; 4 4 4
C= 1 2 3; 1 2 3; 1 2 3; 1 2 3

Evan on 9 Jul 2013
Edited: Evan on 9 Jul 2013
A(sub2ind(size(A),R,C))
Example:
>>A = magic(4);
>>R = [1 1 1; 2 2 2; 3 3 3; 4 4 4];
>>C = [1 2 3; 1 2 3; 1 2 3; 1 2 3];
>>B = A(sub2ind(size(A),R,C))
B =
16 2 3
5 11 10
9 7 6
4 14 15
If you're not talking about a generalized case and just want that particular indexing of any matrix, though, it looks like you just need to trim off part of the matrix:
>>B = A(1:4,1:3);
B =
16 2 3
5 11 10
9 7 6
4 14 15
##### 2 CommentsShowHide 1 older comment
Evan on 9 Jul 2013
Edited: Evan on 9 Jul 2013
Ah, okay. So the row and column indices of every element in your array? I have submitted a new answer below that does this. Note that it looks like your example is for a 3x4 matrix, though, not a 4x3.

Evan on 9 Jul 2013
Edited: Evan on 9 Jul 2013
[R C] = find(A);

Matt J on 9 Jul 2013
[R,C]=ndgrid(1:size(A,1), 1:size(A,2))
##### 2 CommentsShowHide 1 older comment
Matt J on 9 Jul 2013
Edited: Matt J on 9 Jul 2013
Clicking on "Accept this answer" is all the thanks I need ;)