Problem with for loop and if
이전 댓글 표시
I created the following code. The code will open 4 file.txt, extract the value and do some check. The first check is to verify if on the val{1,1}{5,1} ~= 'LIMA'. The problem is that If LIMA isn't on the txt file the programme works fine but when is on the txt file i don't have any output.
Please help me. :-)
fileList = dir( '*.txt' );
for i = 1 : numel( fileList )
nameFile{i} = fileList(i, 1).name;
NAME = char( nameFile(i) );
fid = fopen( NAME );
val (i) = textscan( fid, '%s', 'delimiter', ',' );
fclose( fid );
if val{1,1}{5,1} ~= 'LIMA' %| val{1,1}{6,1} == 'VOCI'
for j = 8 : size(val{1,1},1 )
A(i,j)=str2num( val{1,i}{j,1} );
% end
end
end
end
댓글 수: 1
Jan
2011년 10월 27일
@Maurizio: Please post your questions here instead of sending me emails. This forum lives from public questions and answers.
Have you read my profile?!
답변 (1개)
Jan
2011년 10월 27일
Do not use the == operator to compare strings. The result is an elementwise comparison. Use STRCMP instead.
You import the file data to "val(i)", but check "val{1,1}" in each iteration.
fileList = dir('*.txt');
nameFile = cell(1, numel(fileList)); % Pre-allocate!
for i = 1:numel(fileList)
NAME = fileList(i).name; % [EDITED]
nameFile{i} = NAME;
fid = fopen(NAME);
valC = textscan(fid, '%s', 'delimiter', ',');
val = valC{1};
fclose(fid);
if strcmp(val{5,1}, 'LIMA') == 0
for j = 8:size(val, 1)
A(i, j) = str2num(val{j, 1});
end
end
end
댓글 수: 8
Maurizio
2011년 10월 27일
Jan
2011년 10월 27일
@Maurizio: Please explain, what "is not working" means exactly. Do you get an error message - in which line and which message? Or does the result differ from your expectations? Are you talking about your program or my one?
Maurizio
2011년 10월 27일
Jan
2011년 10월 27일
Oh, well, I made a mistake at defining NAME. You can find such problems by your own using the debugger.
Maurizio
2011년 10월 27일
Jan
2011년 10월 27일
Your can use:
any(strcmp(val{5,1}, {'LIMA', 'PRIMA', 'PUMA'}))
or
s = val{5,1}; if strcmp(s, 'LIMA') || strcmp(s, 'PRIMA') || strcmp(s, 'PUMA')
Maurizio
2011년 10월 28일
Jan
2011년 10월 28일
Of course you can use a FOR loop also. But the shown "any(strcmp(String, Cell-String))" is nicer.
카테고리
도움말 센터 및 File Exchange에서 Entering Commands에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!