フィルターのクリア

String and cell compares?

1 回表示 (過去 30 日間)
luke
luke 2012 年 3 月 27 日
I am having a problem with the below code. I have a field, "name" which I included a sample below. I am trying to do some control break processing, (do some calculations for each group of names, right now I am just counting). The strcmp is not giving me the "right" answer. It always is false and falls through. It seems like I need to convert the cell name into a string or some other conversion.
prevName = name(1);
for ii= 1:5
%length(t_date)
if strcmp(name(1), prevName)
cnt = cnt + 1;
fprintf('test %d\n', cnt)
end
% fprintf('%s == %d\n', cellstr(prevName), cnt);
fprintf('after end\n')
cnt = 0;
prevName = name(ii);
end
name = <53555225x1 cell>
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
'ALCOA INC'
  1 件のコメント
Jan
Jan 2012 年 3 月 27 日
Please use the "{} code" button to format the code. To learn more about the formatting, follow the "Markup help" link on this page.

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

回答 (1 件)

Stephen
Stephen 2012 年 3 月 27 日
I think this is about what you want your code to do. The easiest way to create a cell array of strings is to put the strings in curly braces as shown on the first line. To address the contents of the cell for your fprintf function, you should again use curvy braces, but this time at the end of the variable name, just like you would use parenthesis, except when you use parenthesis on a cell array, Matlab returns a cell. If you use braces will a cell array, matlab returns the contents of the cell. It's a subtle but important difference.
name = {'ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC'}; prevName = name(1); cnt = 0; for ii= 1:5 if strcmp(name(1), prevName) cnt = cnt + 1; fprintf('test %d\n', cnt) end fprintf('%s == %d\n', prevName{1}, cnt); fprintf('after end\n') prevName = name(ii); end
Stephen
  2 件のコメント
Stephen
Stephen 2012 年 3 月 27 日
Code didn't display as intended, trying again:
name = {'ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC','ALCOA INC'};
prevName = name(1);
cnt = 0;
for ii= 1:5
if strcmp(name(1), prevName)
cnt = cnt + 1; fprintf('test %d\n', cnt)
end
fprintf('%s == %d\n', prevName{1}, cnt);
fprintf('after end\n')
prevName = name(ii);
end
luke
luke 2012 年 3 月 27 日
Thanks this works perfectly

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

カテゴリ

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