strcmp isn't comparing properly

19 ビュー (過去 30 日間)
liu James
liu James 2017 年 7 月 2 日
回答済み: Jan 2017 年 7 月 5 日
I'm having trouble figuring out why the strcmp is providing an incorrect output when comparing PSymbol and symbol. The two cells are identical but when comparing strcmp(PSymbol,symbol) it should return a 1 and change location to 1 but it is not. Please help.
% Find the location in the table where symbols are matched
% Symbol is supposed to be unique in P
if strcmp(PSymbol,symbol)
location = i;
% If sides are opposite, flag as a closing transaction
if strcmp(side,oppSide1)
open = 0;
end
end
Ive attached the code and the .mat file. Please help.

採用された回答

Jan
Jan 2017 年 7 月 5 日
Of course strcmp works fine. If you do not get the expected result, the inputs differ from what you think they are. This can be examined using the debugger: Set a breakpoint in the line
if strcmp(PSymbol, symbol)
and check the variables:
class(PSymbol)
class(symbol)
Bother are cells as expected. But do they contain strings?
class(PSymbol{1})
class(symbol{1})
ans =
cell
ans =
cell
No, they contain cells. Therefore strcmp does not get strings or cell strings, but cells containing cell strings. This cannot work. An error message would be nice, but unfortunately strcmp replies false. Solution:
PSymbol = P.symbol{i}; % Curly braces
...
if strcmp(PSymbol, symbol{1})
Now both inputs are cell strings and strcmp replies true.

その他の回答 (1 件)

Image Analyst
Image Analyst 2017 年 7 月 2 日
If they're cell arrays, try ismember() instead of strcmp().
  1 件のコメント
liu James
liu James 2017 年 7 月 2 日
I tried this, but I get this error
Error using cell/ismember (line 34)
Input A of class cell and input B of class cell must be cell arrays of character vectors, unless
one is a character vector.
Error in Open (line 22)
if ismember(PSymbol,symbol)
In this case I don't get what's wrong cause both seems to be cell arrays with characters in it. and both are 1x1 so I would think they are both character vector. Am I missing something?

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

カテゴリ

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