How to sort a table by two columns?

95 ビュー (過去 30 日間)
Anja Lauer
Anja Lauer 2018 年 12 月 5 日
コメント済み: Anja Lauer 2018 年 12 月 6 日
Hello,
I want to sort a table by two column. The table hast three columns in total, one of them is a string. It looks kindof like this:
T= [1 4 'a';
3 2 'b';
1 3 'c';
1 1 'd';
2 5 'e';
3 3 'f';
2 2 'g']
and I want it to look like this:
T_new= [ 1 1 'd';
1 3 'c';
1 4 'a';
2 2 'g';
2 5 'e':
3 2 'b';
3 3 'f']
I tried using the Function:
T=sortrows(T,[1 2]);
but it only sorts the first column but not the second:
T_false= [ 1 4 'a';
1 3 'c';
1 1 'd';
2 5 'e';
2 2 'g';
3 2 'b';
3 3 'f']
I think it's pry because of the third column being a string because I have been using this function befor with only numeric matrices and it worked fine.
I would be thankful for any tipps.
Thank you, Anja

採用された回答

Kevin Chng
Kevin Chng 2018 年 12 月 5 日
編集済み: Kevin Chng 2018 年 12 月 5 日
I follow your solution, it sorts two columns for me.
See :
a = [1 3 1 1 2 3 2];
b = [4 2 3 1 5 3 2];
c = ['a' 'b' 'c' 'd' 'e' 'f' 'g'];
t=table(a',b',c');
t = sortrows(t,[1,2])
Result :
T =
7×3 table
Var1 Var2 Var3
____ ____ ____
1 1 d
1 3 c
1 4 a
2 2 g
2 5 e
3 2 b
3 3 f
  3 件のコメント
Kevin Chng
Kevin Chng 2018 年 12 月 5 日
Hi Anja,
Your updated one is correct, there are many unseen decimal point. try:
format long
load testtable.mat
H = sortrows(H,[1,2]);
%display the top 10, then you will understand
H(1:,10,:)
from the code above, you will understand since some decimal point is hidden.
Accept my answer if it answers your question.
Anja Lauer
Anja Lauer 2018 年 12 月 6 日
I did not think about the hidden decimal points! Thank you so much! I know what to do now!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by