How can I sort a matrix elementwise ?

2 ビュー (過去 30 日間)
Gayan Lankeshwara
Gayan Lankeshwara 2019 年 10 月 21 日
コメント済み: Gayan Lankeshwara 2019 年 10 月 21 日
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.

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 10 月 21 日
A = [3, 4 ; 6, 2];
[m,~] = size(A);
[B,i] = sort(A(:));
index = [mod(i-1,m) + 1, ceil(i/m)];
  1 件のコメント
Gayan Lankeshwara
Gayan Lankeshwara 2019 年 10 月 21 日
Hi Andrei,
I tried the code and this is what I wanted.
Thank you.

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

その他の回答 (1 件)

Stephan
Stephan 2019 年 10 月 21 日
B = sort(reshape(A,[],1))
  3 件のコメント
Stephan
Stephan 2019 年 10 月 21 日
[B, idx] = sort(reshape(A,[],1))
[row,col] = ind2sub([size(A,1), size(A,2)],idx)
Gayan Lankeshwara
Gayan Lankeshwara 2019 年 10 月 21 日
Hi Stephan,
This is really what I needed and the inbuilt in2sub function is more powerful I guess.
Thanks.

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

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by