How to sort or rearrange a column with respect to the other column?!

22 ビュー (過去 30 日間)
Mariam Sheha
Mariam Sheha 2016 年 6 月 17 日
コメント済み: Mariam Sheha 2016 年 6 月 17 日
Hello Everybody;
wish you are all doing well;
if i have a data of two columns and i want to sort one of the columns in a descending order and also keep the other column fixed and likened with the changed one, how can i do that?! assuming that column 1 is the ID of column two
sample data:
241 5
1245 4
684 4
806 4
674 3
Appreciating your help ;

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 6 月 17 日
編集済み: Azzi Abdelmalek 2016 年 6 月 17 日
Use sortrows function. For example
A=[241 5;1245 4;684 4;806 4;674 3]
B=sortrows(A,2)
% Or by descending order
B=sortrows(A,-2)
  5 件のコメント
Guillaume
Guillaume 2016 年 6 月 17 日
Please, read the documentation of sortrows. You can sort according to whichever column and whichever direction you wish.
The documentation contains lots of useful information!
Mariam Sheha
Mariam Sheha 2016 年 6 月 17 日
thanks it is brilliant :)

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

その他の回答 (1 件)

Shameer Parmar
Shameer Parmar 2016 年 6 月 17 日
編集済み: Shameer Parmar 2016 年 6 月 17 日
Hello Mariam,
For your given sample data:
A =
241 5
1245 4
684 4
806 4
674 3
use following code:
A = [241, 5; 1245, 4; 684, 4; 806, 4; 674, 3];
B(:,1) = sort(A(:,1),'descend');
for i=1:length(A)
B(i,2)=A(find(ismember(A(:,1),B(i))),2);
end
B
OutPut will be like in '*descending*' order
B =
1245 4
806 4
684 4
674 3
241 5
  3 件のコメント
Guillaume
Guillaume 2016 年 6 月 17 日
Both sortrows and sort allows you to specify the direction. I recommend using sortrows as it's more suited to what you want.
If you were to use sort, I would use the 2nd return value to reorder the other columns rather than a loop and ismember:
[B(:, 1), order] = sort(A(:, 1), 'descend');
B(:, 2) = A(order, 2);
As said, sortrows as per Azzi's answer is better.
Mariam Sheha
Mariam Sheha 2016 年 6 月 17 日
thanks for your quick answer and recommendation is appreciated :)

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by