fprintf error using GA algorithm

9 次查看(过去 30 天)
Liset Geijselaers
Liset Geijselaers 2016-11-19
回答: Jan 2016-11-19
I made a model that is optimized using a GA algorithm so I have to run the model many times. This model included a moment where I need to calculate something with a .exe file. For this file I need to save some data in .dat files. I am saving this data using fprintf as can be seen below.
[fid msg]=fopen('track.dat','w');
fprintf(fid,'Sys\n');
fprintf(fid,'==================================================================\n');
fprintf(fid,'met\n\n');
fprintf(fid,'%10s\t%10s\t%10s\t%10s\t%10s\t%10s\n','x','y','h','V','T','m');
fprintf(fid,'==================================================================\n');
fprintf(fid,'%10.3f\t%10.3f\t%10.3f\t%10.3f\t%10.3f\t%10.0f\n',INM_data');
fprintf(fid,'\n==================================================================\n');
fprintf(fid,'%6s\r\n',c.ET);
fprintf(fid,'%6s\r\n',c.EM);
fclose(fid);
x_min=round((min(x_arr)-8000)/100)*100;
x_max=round((max(x_arr)+8000)/100)*100;
y_min=round((min(y_arr)-8000)/100)*100;
y_max=round((max(y_arr)+8000)/100)*100;
[fid2 msg]=fopen('grid2D.dat','w');
fprintf(fid2,'%10s\t%10s\t%10s\t%10s\t%10s\t%10s\r\n','x_min','x_max','x_sz','y_min','y_max','y_sz');
fprintf(fid2,'==================================================================\n');
fprintf(fid2,'%10f\t%10f\t%10f\t%10f\t%10f\t%10f\r\n',x_min,x_max,500,y_min,y_max,500);
fclose(fid2);
status=system('INMmodel.exe track.dat grid2D.dat' );
delete('track.dat','grid2D.dat');
As can be seen I open the files, I write something, close them and then even delete them after I have used to run the .exe file.
I run the optimization problems for over 200 generations and with a population of 50. The error occurs random, or at least I don't see any pattern in it. The message I get:
fid = -1
msg= Permission denied
And then with the next line I get an error in fprintf saying:
Invalid file identifier. Use fopen to generate a valid file identifier.
Does anybody have any idea why this keeps happening and how to solve this? So I can finish a full optimization problem.

回答(1 个)

Jan
Jan 2016-11-19
The message means, that the file cannot be opened for writing. Either it is opened by another program or you do not have write permissions in the current folder. Do not rely the current folder to be, what you are expecting, because a GUI oder TIMER-callback might change it. Better use absolute file names including the path.
file = fullfile(tempdir, 'track.dat');
[fid, msg] = fopen(file, 'w'); % Or your folder
if fid == -1 % Always check the success
error('Cannot open file: %s\nProblem: %s', file, msg);
end

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by