Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

(quick) Matlab fprintf question

  1. Aug 23, 2012 #1
    I have output (stored in variable "x") that I want saved into a simple text file. If I use the command:


    it prints the data in a nice column. This is what I want. Then to save it to a file I try this:

    fileID = fopen('x.txt');

    however Matlab does not like this. When I searched the help file, it gave a similar example, so what am I doing wrong here? Thanks in advance!
  2. jcsd
  3. Aug 24, 2012 #2


    User Avatar
    Science Advisor

    Try specifying the file ID as the first parameter.

    fileID = fopen('x.txt');
  4. Aug 24, 2012 #3
    Thanks for the help, but unfortunately it did not work. I still get this error from Matlab:

    Error using fprintf
    Invalid file identifier. Use fopen to generate a valid file identifier.

    when I try my code:

    fileID = fopen('x.txt');

    the error I get is:

    Error using fclose
    Invalid file identifier. Use fopen to generate a valid file identifier.

    I still can't figure out why?
  5. Aug 24, 2012 #4


    Staff: Mentor

    When you open the file, you need to specify the permission, which is related to what you want to do with the file (read it, write to it, and so on).

    Here's a link to some documentation for fopen: http://amath.colorado.edu/computing/Matlab/OldTechDocs/ref/fopen.html [Broken].

    Try this:
    Code (Text):

    fileID = fopen('x.txt', 'wt');
    I don't have MATLAB, so can't verify that this will work, but I think it will.
    Last edited by a moderator: May 6, 2017
  6. Aug 24, 2012 #5


    User Avatar
    Science Advisor

    Ok, well in that case it appears that your problem is with the fopen statement (BTW. Is there any particular reason why you didn't post the actual error message in the first place!)

    Try letting it know that the file doesn't currently exit and that you wish to create it.

    fileID = fopen('x.txt','w');

    This tells it that you want to open the file for writing.
  7. Aug 24, 2012 #6
    Thanks! I really can't think of why I did not post the error in the first place, except that I've not had much sleep :)

    Edit: OK, got it! Thanks everyone for the help!!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Similar Threads for quick Matlab fprintf Date
Quick Matlab Query Feb 21, 2014
How to Become MATLAB Expert Quickly Jan 9, 2012
A quick question regarding matlab Oct 3, 2011
Matlab quick question Dec 1, 2009
Quick matlab question Jun 2, 2008