Filter löschen
Filter löschen

String and cell compares?

1 Ansicht (letzte 30 Tage)
luke
luke am 27 Mär. 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 Kommentar
Jan
Jan am 27 Mär. 2012
Please use the "{} code" button to format the code. To learn more about the formatting, follow the "Markup help" link on this page.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen
Stephen am 27 Mär. 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 Kommentare
Stephen
Stephen am 27 Mär. 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 am 27 Mär. 2012
Thanks this works perfectly

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by