Nested loops not working

조회 수: 6 (최근 30일)
Mak
Mak 2017년 5월 30일
편집: Mak 2017년 5월 31일
Hi!
Been working at this problem for hours and just can't figure it out.
The FOR loop goes through numbers [9 11 12] and the WHILE loop is supposed to execute on each of the three iterations of the FOR loop. However, the FOR loop goes through all 3 iterations and then the while loop executes for the last iteration of the FOR loop. Why is the WHILE loop skipped on the first two iterations of the FOR loop?
Thanks a million to anyone who can help!
fid2=fopen('allMeasurements.txt','at');
for i = [9 11 12]
s1=num2str(i);%Next lines creat filename
if i<10;
s0='0';
s1=strcat(s0,s1);
end
s0='000';
s=strcat(s0,s1,'.txt');
sd='data';
s=strcat(sd,s)
fid=fopen(s, 'rt');
while feof(fid)==0;%This loop goes through every even line of file
tline = fgetl(fid);
if mod(i,2)==1;
continue
end
A = sscanf(tline,'%f', [1,4]);%The 4 colums are sotred in A
B = A(3:end);%The last two colums are written to file
fprintf(fid2,'%f %f\n',B);
end
fclose(fid);
end
fclose(fid2);
  댓글 수: 2
Rik
Rik 2017년 5월 30일
Try going through your code with breakpoints so you can follow the flow of your code step by step.
Also, you can use s=sprintf('data%05d.txt',i) to make your code look more elegant (and compatible with i>99).
Mak
Mak 2017년 5월 31일
편집: Mak 2017년 5월 31일
SOLVED
I was insanely mixing up two the two loops:D
Thanks

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2017년 5월 30일
However, the FOR loop goes through all 3 iterations and then the while loop executes for
the last iteration of the FOR loop
I cannot confirm your opinion. Why do you assume that this happens?
folder = cd; % Define it explicitely!
fid2 = fopen(fullfile(folder, 'allMeasurements.txt'), 'at');
if fid == -1
error('Cannot open file for appending');
end
for i = [9 11 12]
file = fullfile(folder, sprintf('data%05d.txt',i));
fid = fopen(file, 'rt');
if fid == -1
error('Cannot open file for reading: %s', file);
end
while feof(fid)==0 %This loop goes through every even line of file
tline = fgetl(fid);
if mod(i,2) == 0
A = sscanf(tline, '%f', [1,4]);%The 4 colums are sotred in A
fprintf(fid2, '%f %f\n', A(3:end));
end
end
fclose(fid);
end
fclose(fid2);
Perhaps the checks for successful opening the files will help.

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by