Problem with creating .dat file

1 view (last 30 days)
Giovanni Ponce
Giovanni Ponce on 17 Apr 2022
Answered: Voss on 20 Apr 2022
Hello, I have a problem with this part of a code. could someone tell me if it has something to do with path of the file? I want to replace windcity.dat file and create my own .dat file for MATLAB. I using MAC and I tried (text editor>make plain text>and save as UTF-8) but I still get .txt at the end. I want to create an import file of my owm with .dat so I can output values.
% Open simulation output file and write header
if ( ~exist('theSimfile', 'var') )
simfile = 'Users/ponce/Desktop/folder 10/windcity.dat';
end
simfid = fopen( theSimfile, 'w' );
fprintf( simfid, ['#state1\tstate2\tstate3\tstate4\tstate5\n', ...
'original1\toriginal2\toriginal3\toriginal4\toriginal5\toriginal6\n', ...
'error1\terror2\terror3\terro4\n'] );
It is giving me this error:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in windbess (line 77)
fprintf(simfid, ['#state1\tstate2\tstate3\tstate4\tstate5\n', ...
'original1\toriginal2\toriginal3\toriginal4\toriginal5\toriginal6\n', ...
'error1\terror2\terror3\terro4\n'] );

Answers (1)

Voss
Voss on 20 Apr 2022
You check if the variable theSimfile exists, and if it doesn't, you create a variable called simfile. Then you use theSimfile (which may not exist) in fopen, and simfile (which also may not exist) is unused.
I imagine that the intent in checking for the existence of a variable is to use a default file if it is not already specified, but probably the variable you create should be the one you just found not to exist (doesn't matter if it's called simfile or theSimfile). Then use that same variable in fopen.
Also, in case the file can't be opened for whatever reason, you can take the second output from fopen and throw it as an error.
(And don't forget to fclose the file.)
if ~exist('simfile','var')
simfile = 'Users/ponce/Desktop/folder 10/windcity.dat';
end
[simfid,simmsg] = fopen( simfile, 'w' );
if simfid == -1
error(simmsg);
end
fprintf( simfid, ['#state1\tstate2\tstate3\tstate4\tstate5\n', ...
'original1\toriginal2\toriginal3\toriginal4\toriginal5\toriginal6\n', ...
'error1\terror2\terror3\terro4\n'] );
% close the file when you are done writing!
fclose( simfid );

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!