sort( ) do not work (or?)

9 ビュー (過去 30 日間)
Martin
Martin 2015 年 8 月 13 日
編集済み: Stephen23 2015 年 8 月 17 日
Hello, Got a strange problem with the sort( ) function (I tried with sortrows as well, - same problem exist)..
I just attached the result of two different data tests. In both tests, I show the not sorted data, and the sorted data.. Each number is taken from a 1x1 cell.
Why can it be, that it does not sort the second test?
Hope to hear from someone, thanks in advance.
-best
  1 件のコメント
James Tursa
James Tursa 2015 年 8 月 13 日
Please show us the code you are using.

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

採用された回答

dpb
dpb 2015 年 8 月 13 日
Both are sorted, but as the quotes around the data show the data are stored as cell strings so it's in ASCII order, not numeric. Convert the cellstring array to numeric prior to sorting...
sort(str2num(char(x)))
or equivalent where x is the cell array.
The first looks ok because all are of the same order of magnitude between 0-1 while the latter change. If you note, they're sorted by the first character of the number in order first.
  3 件のコメント
Stephen23
Stephen23 2015 年 8 月 14 日
編集済み: Stephen23 2015 年 8 月 17 日
You could also use my FEX submission natsort, which sorts strings while taking into account the values of any numbers inside the strings (i.e. it provides a natural-order string sort):
>> X = {'9.246556','16.869455','9.781987','17.742497','8.356578','11.972240','8.085880','11.425893'};
>> natsort(X,'\d+\.\d+')
ans =
8.085880
8.356578
9.246556
9.781987
11.425893
11.972240
16.869455
17.742497
Yes, those are strings in the output, not numerics!
Martin
Martin 2015 年 8 月 14 日
thanks for more knowledge! This problem has puzzled me a lot, but now I finally understand it. And my code works as I want it to.

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

その他の回答 (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