How can I sort a matrix elementwise ?

8 visualizzazioni (ultimi 30 giorni)
Hi, I need to sort a matrix elementwise and get the results to a single vector without losing the index of each element.
For example,
A = [3, 4 ; 6, 2]
The sorted vector should be ,
B = [2;3;4;6]
without losing the information of each and every element in the original matrix.
Thank you.

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 21 Ott 2019
A = [3, 4 ; 6, 2];
[m,~] = size(A);
[B,i] = sort(A(:));
index = [mod(i-1,m) + 1, ceil(i/m)];
  1 Commento
Gayan Lankeshwara
Gayan Lankeshwara il 21 Ott 2019
Hi Andrei,
I tried the code and this is what I wanted.
Thank you.

Accedi per commentare.

Più risposte (1)

Stephan
Stephan il 21 Ott 2019
B = sort(reshape(A,[],1))
  3 Commenti
Stephan
Stephan il 21 Ott 2019
[B, idx] = sort(reshape(A,[],1))
[row,col] = ind2sub([size(A,1), size(A,2)],idx)
Gayan Lankeshwara
Gayan Lankeshwara il 21 Ott 2019
Hi Stephan,
This is really what I needed and the inbuilt in2sub function is more powerful I guess.
Thanks.

Accedi per commentare.

Categorie

Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by