fopen just works inside of a loop

12 views (last 30 days)
Hello,
I currently have a performance problem which should be easy to solve i think. The code here is a minimalistic example of the problem. It´s in 2 seperate .m-files. The "main" function (which is an optimizer) calls the "loop" function with the given values. The "loop" function calls the other m.-file "dothat" in every while-loop.
function main
a = 2;
b = 3;
loop(a, b)
end
function value = loop(a, b)
while a <= 20
dothat
a = a + b;
end
end
The "dothat" file needs additional data from a .txt - file in every loop to interpolate a value (in the example just shows a text).
b = b+1;
fid = fopen('example.txt' , 'r');
tline = fgetl(fid)
That works fine, but in the real code the while loop "loops" a few thousand times so i also have to add an fclose command in the "dothat" file to prevent the "too many files open" error. So the code opens and closes the files thousands of times, and the simulation needs minutes instead of seconds. Is there a way to get the fopen-command out of the loop? It just works when fopen is in the "dothat" file or in the "loop" function, but just inside of the while-loop. Otherwise MATLAB cant open the file or doesn´t know "fid".
Thanks for any help, files are in the attachments!
  4 Comments
Chris Topher
Chris Topher on 10 Nov 2020
It seems like it only remembers the file for one loop.
Chris Topher
Chris Topher on 10 Nov 2020
I uploaded everything in the original question.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 10 Nov 2020
Your dothat.m has a call to fopen() in it. But nowhere do you have a call to fclose(). Why not? You should. If you're opening the same file, you should open it just once, before the loop, and close it after the loop:
function value = loop(a, b)
fid = fopen('example.txt' , 'rt'); % Open text file as 'rt' just once.
while a <= 20
dothat % Must not have a call to fopen() in this function.
a = a + b;
end
fclose(fid)
end
and do NOT have a call to fopen in dothat.m.
If you need to do sequential access on fid using fgetl(), then it's possible you might want to rewind the pointer, depending on if you need to check the file from the beginning or not.
frewind(fid);
  2 Comments
Chris Topher
Chris Topher on 10 Nov 2020
Thank you! It now works perfectly with just putting a frewind(fid) at the end of every loop. That´s what I´ve needed and it makes perfectly sense.
Image Analyst
Image Analyst on 10 Nov 2020
OK, but you still need to use fclose() at some point. Don't forget that!!!

Sign in to comment.

More Answers (1)

Fangjun Jiang
Fangjun Jiang on 9 Nov 2020
Whatever data you need from the text file, you could read it once, store it in a variable and use it in the loop. You wouldn't drive your car to a store 5 times in a roll back and forth to buy 5 items

Community Treasure Hunt

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

Start Hunting!