How to Compare strings

12 ビュー (過去 30 日間)
Pap
Pap 2011 年 4 月 30 日
Hello,
I need to compare strings and sort in (even in alphabetical order) but without using
the sort code.
I run a code and I get the error message:
Undefined function or method 'gt' for input arguments of type 'cell'.
Error in ==> Untitled3 at 16 if stock(b)>stock(b+1)
Can anyone help on how to solve this or how to compare strings, or how to convert strings to numbers in order to compare them?
Many thanks
Panos

採用された回答

Jan
Jan 2011 年 5 月 1 日
You want to operate on the cell elements, not on scalar cells:
if stock(b) > stock(b+1)
% ==>
if stock{b} > stock{b+1} % Curly braces!
This works, if both strings have the same length. A conversion to a numerical is not needed. If the strings have different length, pad the shorter one with zeros:
char0 = char(0);
s1 = stock{b};
s2 = stock{b+1};
len1 = length(s1);
len2 = length(s2);
if len1 > len2
s2 = [s2, char0(1, len1 - len2)];
elseif len2 > len1
s1 = [s1, char0(1, len2 - len1)];
end
if s1 > s2 ...

その他の回答 (1 件)

Robert Cumming
Robert Cumming 2011 年 4 月 30 日
Have you tried:
strcmp
to convert to numbers
str2num
  2 件のコメント
Pap
Pap 2011 年 4 月 30 日
thanks,
I need to sort string alphabetically. So I can't use strcmp.
actually I have a txt file of 6 columns and 100000 rows, saved as six 1x100000 cell arrays. I want to sort all the rows with respect to the first cell array (alphabetically)
Any hint?
Robert Cumming
Robert Cumming 2011 年 5 月 1 日
why cant you use sort?

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by