MATLAB: I am having a error using fprintf

error fprintf

Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in main (line 159)
fprintf(f_id,'nx,ny, total: %6d %6d %12d \n', nx, ny,(2*nx+1)*(2*ny+1));
Here is the code chunck:
%---------- file output --------------------
dat_str = datestr(now,'yyyymmmdd@HH:MM');
eps_name = ['./results/inc',num2str(inc_disk*180/pi),'a',num2str(a),...
'_',dat_str,'.eps']; %output eps file name
txt_name = ['./results/BRT_',dat_str,'.txt'];
f_id = fopen(txt_name,'wt'); % export the data as ascii
%----- generate the output to a text file ----------
fprintf(f_id,'nx,ny, total: %6d %6d %12d \n', nx, ny,(2*nx+1)*(2*ny+1));
fprintf(f_id,'no. of rays hitting the disk, %10d \n', numb_disk);
fprintf(f_id,'no. of rays hitting black hole, %10d \n', numb_hole);
fprintf(f_id,'no. of rays from higher order images, %10d,\n', numb_high);
fprintf(f_id,'g_max = %12.4f, g_min = %12.4f \n', g_max, g_min);
fprintf(f_id,'mag_flux = %12.4f, mag_area = %12.4f \n',mu_flux, mu_area);
fprintf(f_id,'maximum error in Carter constant,%14.4E \n ', err_Q_max);
fprintf(f_id,'Degree of polarization: %f14.4 \n', del_total);
fprintf(f_id,'Angle of polarization chi (deg): %f14.4\n',chi_total*180/pi);
fprintf(f_id,'number of workers %8d \n',num_workers);
fprintf(f_id,'RT speed (rays per second) = %12.4f \n', rate_BRT);
fprintf(f_id,'Wall clock time (hours): %f14.4 \n', t_hour);
fclose(f_id);
Thank you

Best Answer

You should always return the second output of fopen and check the f_id value:
[f_id,msg] = fopen(txt_name,'wt');
assert(f_id>=3,msg)
The cause is, as Bob Nbob already wrote, likely to be that the file could not be found/created. Typically this occurs if the path name is not correct, or you do not have write permission for that location. You will have to check the path name using exist, check your user permissions, etc.