String and cell compares?

1 vue (au cours des 30 derniers jours)
luke
luke le 27 Mar 2012
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 commentaire
Jan
Jan le 27 Mar 2012
Please use the "{} code" button to format the code. To learn more about the formatting, follow the "Markup help" link on this page.

Connectez-vous pour commenter.

Réponses (1)

Stephen
Stephen le 27 Mar 2012
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 commentaires
Stephen
Stephen le 27 Mar 2012
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 le 27 Mar 2012
Thanks this works perfectly

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by