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!