- have spelling mistake in the filename.
- try to open a file that does not exist.
- don't put the required path information, even though the file is located somewhere other than the current directory.
- try to read or write to a location where they do not have permission.
How to use fprintf in Matlab R2016a
1 view (last 30 days)
Show older comments
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)');
0 Comments
Accepted Answer
Stephen23
on 9 Jun 2016
Edited: Stephen23
on 9 Jun 2016
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:
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.
5 Comments
Stephen23
on 9 Jun 2016
Edited: Stephen23
on 9 Jun 2016
So, finally lets have a look a the information you have given us:
P =
C:\Program Files\MATLAB\R2016a\bin
msg =
Permission denied
The path is somwhere in the MATLAB installation directory. Why are you trying to save there? Quite rightly, Windows is stopping you (as the message clearly says) from saving or altering files inside the program directory. This has nothing to do with MATLAB, and is caused by that fact that you are trying to save a file somewhere where you are not (normally) allowed to. Your OS is stopping you from damaging your installed programs!
The solution is to save your file somewhere where you do have permission. Normally this would be in the users' directories. You might also need to change the MATLAB current directory, as it should definitely not be inside the program files directory.
More Answers (1)
Jos (10584)
on 9 Jun 2016
The problem is with fopen. Did you check the value of fileID?
Most likely, you do not have the permission to write in the current folder.
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!