extracting row and column indices from MatLab matrix

7 次查看(过去 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?

采纳的回答

Jos (10584)
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
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
Guillaume 2016-2-24
Note that you may want to use
fprintf('%5g ',D_input)
If the D_input can contain non-integer numbers
Laszlo Bodnar
Laszlo Bodnar 2016-2-25
Thank you Stephen & Guillaume for your replies. Although I will use Jos's code in my exercise, I will also memorize your solution which is quite elegant and surely come in handy later on. Thanks again.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by