MATLAB: How to use fprintf in Matlab R2016a

how to use fprintf

I am working with Matlab R2016a, and I get error for the follwing code which is form mathworks's website.
The thing is whenever I use fprintf, I get the same error.
Thanks a lot for the help.
x = 0:.1:1;
A = [x; exp(x)];
fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);
Error:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in Untitled (line 5)
fprintf(fileID,'%6s %12s\n','x','exp(x)');

Best Answer

The problem really has nothing to do with fprintf, it is actually because fopen cannot open the file that you are telling it to. This typically happens to beginners when they do one of these:
  1. have spelling mistake in the filename.
  2. try to open a file that does not exist.
  3. don't put the required path information, even though the file is located somewhere other than the current directory.
  4. try to read or write to a location where they do not have permission.
You can find what fopen says about its troubles by having a look at its second output:
[fileID,msg] = fopen('exp.txt','w');
What is the information in msg ? What does it say ?
For every case (except the last) the solution is always the same: provide fopen with the correct path information. The last case has nothing to do with MATLAB: if a user does not have permission for a folder then this is not MATLAB's problem.