extracting row and column indices from MatLab matrix
조회 수: 5 (최근 30일)
이전 댓글 표시
I have a simple matrix that I have imported into MatLab using the following code:
D_input=[0 1 2 1 ; nan 0 2 1 ; nan nan 0 1 ; nan nan 1 0];
D_input
Now what I want to do is I would like to see the outputs in vector format, so I applied the following code:
reshape(D_input,1,numel(D_input))
It works perfectly fine:
0 NaN NaN NaN 1 0 NaN NaN 2 2 0 1 1 1 1 0
Now is there a way to display the row and column indices above this result, I mean something like this:
(a – using row col indices)) (1,1) (2,1) (3,1) (4,1) (1,2) (2,2) (3,2) etc.
(b – using linear indexing) 1 2 3 4 5 6 7 etc.
(c – output) 0 NA NA NA 1 0 NA etc.
I know about version b (linear indexing) but still I would prefer version a, displaying the row and column indices of D_input matrix as indicated. Is there an easy way to do this?
댓글 수: 0
채택된 답변
Jos (10584)
2016년 2월 24일
You can transform linear indices into subindices, and vice versa using ind2sub and sub2ind
A = [99 NaN ; 8 7 ; 1 0]
LinearIndices = 1:numel(A)
[RowInd, ColInd] = ind2sub(size(A), 1:numel(A))
추가 답변 (1개)
Stephen23
2016년 2월 24일
편집: Stephen23
2016년 2월 24일
D_input = [0 1 2 1 ; nan 0 2 1 ; nan nan 0 1 ; nan nan 1 0]
S = size(D_input);
[X,Y] = ndgrid(1:S(1),1:S(2));
fprintf(' (%d,%d)',[X(:)';Y(:)'])
fprintf('\n')
fprintf('%5d ',1:prod(S))
fprintf('\n')
fprintf('%5d ',D_input)
fprintf('\n')
displays this in the command window:
(1,1) (2,1) (3,1) (4,1) (1,2) (2,2) (3,2) (4,2) (1,3) (2,3) (3,3) (4,3) (1,4) (2,4) (3,4) (4,4)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
0 NaN NaN NaN 1 0 NaN NaN 2 2 0 1 1 1 1 0
Note: this solution works for integer values with fewer than five digits, and matrices with size less than 10 along any dimension. For larger numbers or matrices you will need to play around with the spacing and fieldwidth of the fprintf format tokens.
댓글 수: 2
Guillaume
2016년 2월 24일
Note that you may want to use
fprintf('%5g ',D_input)
If the D_input can contain non-integer numbers
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!