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

조회 수: 12 (최근 30일)
Antonio Trujillo-Ortiz
Antonio Trujillo-Ortiz 2013년 7월 9일
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
Thx in advance.

답변 (3개)

Evan
Evan 2013년 7월 9일
편집: Evan 2013년 7월 9일
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
Antonio Trujillo-Ortiz
Antonio Trujillo-Ortiz 2013년 7월 9일
Hi Evan,
What I need is to get from any matrix, two new ones with its row and column indexes. I mean,
Eg, given
A = [2 5 6;12 7 0;2 9 7;4 17 1 0]
we have 4 rows and 3 columns, and we need to get matrices
R = [1 1 1;2 2 2;3 3 3;4 4 4]
and
C = [1 2 3;1 2 3;1 2 3;1 2 3]
Thx
Evan
Evan 2013년 7월 9일
편집: Evan 2013년 7월 9일
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
Evan 2013년 7월 9일
편집: Evan 2013년 7월 9일
[R C] = find(A);

Matt J
Matt J 2013년 7월 9일
[R,C]=ndgrid(1:size(A,1), 1:size(A,2))
  댓글 수: 2
Antonio Trujillo-Ortiz
Antonio Trujillo-Ortiz 2013년 7월 9일
Thanks Matt J. Its just what I need.
Matt J
Matt J 2013년 7월 9일
편집: Matt J 2013년 7월 9일
Clicking on "Accept this answer" is all the thanks I need ;)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by