フィルターのクリア

Sorting a matrix by one column

4 ビュー (過去 30 日間)
José Pereira
José Pereira 2017 年 12 月 7 日
コメント済み: José Pereira 2017 年 12 月 7 日
So i have this "matrix". First column is names, second colomn is passwords. I want to display this data alphabetically by name. I don´t know how to do this.So here is the original matrix,
{'john'} {'jojo'}
{'victor'} {'vivi'}
{'andre'} {'dredre'}
and here is the result i want to display:
{'andre'} {'dredre'}
{'john'} {'jojo'}
{'victor'} {'vivi'}
Thanks!

採用された回答

KL
KL 2017 年 12 月 7 日
編集済み: KL 2017 年 12 月 7 日
That's not a matrix. If you meant to store them in cell arrays,
C = {'john', 'jojo';'victor', 'vivi';'andre', 'dredre'};
It would look like
C =
6×1 cell array
'john' 'jojo'
'victor' 'vivi'
'andre' 'dredre'
Now use just sortrows
C = sortrows(C,1)
3×2 cell array
'andre' 'dredre'
'john' 'jojo'
'victor' 'vivi'
Neverthless better idea to store such data is to use tables,
names = {'John';'victor';'andre';};
passwords= {'jojo';'vivi';'dredre'};
T = table(passwords,'RowNames',names)
and it looks like,
T =
3×1 table
passwords
_________
John 'jojo'
victor 'vivi'
andre 'dredre'
now, again sortrows,
sortrows(T)
3×1 table
passwords
_________
andre 'dredre'
John 'jojo'
victor 'vivi'
  3 件のコメント
KL
KL 2017 年 12 月 7 日
If you are still opting to use cell array, then simply use sort and only for first column. Extract the sorted indices from the result and use it sort the original cell array.
C = {'john', 'jojo';'victor', 'vivi';'andre', 'dredre'}
[~,indx] = sort(C(:,1));
sortedC = C(indx,:)
sortedC =
3×2 cell array
'andre' 'dredre'
'john' 'jojo'
'victor' 'vivi'
José Pereira
José Pereira 2017 年 12 月 7 日
That is exactly what i wanted. Thanks

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by