フィルターのクリア

extracting row and column indices from MatLab matrix

7 ビュー (過去 30 日間)
Laszlo Bodnar
Laszlo Bodnar 2016 年 2 月 24 日
コメント済み: Laszlo Bodnar 2016 年 2 月 25 日
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 件のコメント
Laszlo Bodnar
Laszlo Bodnar 2016 年 2 月 25 日
Thank you Jos for the quick help!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeStatistics 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