Borrar filtros
Borrar filtros

extracting row and column indices from MatLab matrix

7 visualizaciones (últimos 30 días)
Laszlo Bodnar
Laszlo Bodnar el 24 de Feb. de 2016
Comentada: Laszlo Bodnar el 25 de Feb. de 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?

Respuesta aceptada

Jos (10584)
Jos (10584) el 24 de Feb. de 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))

Más respuestas (1)

Stephen23
Stephen23 el 24 de Feb. de 2016
Editada: Stephen23 el 24 de Feb. de 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 comentarios
Guillaume
Guillaume el 24 de Feb. de 2016
Note that you may want to use
fprintf('%5g ',D_input)
If the D_input can contain non-integer numbers
Laszlo Bodnar
Laszlo Bodnar el 25 de Feb. de 2016
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by