Nested loops not working

1 次查看(过去 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 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by