String and cell compares?
2 次查看(过去 30 天)
显示 更早的评论
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
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
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
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!