extracting row and column indices from MatLab matrix
5 views (last 30 days)
Show older comments
Laszlo Bodnar
on 24 Feb 2016
Commented: Laszlo Bodnar
on 25 Feb 2016
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 Comments
Accepted Answer
Jos (10584)
on 24 Feb 2016
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))
More Answers (1)
Stephen23
on 24 Feb 2016
Edited: Stephen23
on 24 Feb 2016
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 Comments
Guillaume
on 24 Feb 2016
Note that you may want to use
fprintf('%5g ',D_input)
If the D_input can contain non-integer numbers
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!