Nested loops not working

1 vue (au cours des 30 derniers jours)
Mak
Mak le 30 Mai 2017
Modifié(e) : Mak le 31 Mai 2017
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 commentaires
Rik
Rik le 30 Mai 2017
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 le 31 Mai 2017
Modifié(e) : Mak le 31 Mai 2017
SOLVED
I was insanely mixing up two the two loops:D
Thanks

Connectez-vous pour commenter.

Réponses (1)

Jan
Jan le 30 Mai 2017
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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by