Feed on
Posts
Comments

[update: a much easier solution]save ‘my_file.name’ my_array_or_matrix -ASCII -TABS

to write a file in matlab, you first need to get a file id:

>> fid = fopen(‘nameofyourfile.txt’,'w’)

(the ‘w’ means that this file will completely overwrite whatever file shares the same filename)

to write to the file, use the fprint command:

>> fprintf(fid,’%d’,5);

this puts the number 5 into nameofyourfile.txt.

to prevent the file handling gnomes from attacking you in the night, be sure to close the file when you’re finished writing all of your data:

>> fclose(fid);


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

10 Responses to “write an array (or other data) to a file in matlab”

  1. on 25 Apr 2008 at 6:18 am deine mutter

    hi there,

    isn’t it supposed to be fprintf(fid,’%d’,5); ?

    greetings

  2. on 30 Apr 2008 at 8:40 am Lawrence David

    why yes it is! thanks deine! this post has been duly updated.

  3. on 16 Jul 2008 at 2:20 pm Trevor

    OOPS
    you’re instructions are wrong, good sir.

    >> fprintf(fid,ā€™%dā€™,5);
    ??? fprintf(fid,ā€™%dā€™,5);
    |
    Error: The input character is not valid in MATLAB statements or expressions.

  4. on 24 Jul 2008 at 12:02 pm Dewey

    Whats the difference between the statements? They all look the same to me. Am I missing something?

  5. on 20 Aug 2008 at 8:34 am Lawrence David

    hi trevor — you might want to check that when you copy and paste, you’re using single quotes, instead of backticks!

  6. on 25 Sep 2008 at 10:38 am Angi

    this is not really writing an array to a file. it is writing one number into a file. How do you handle the command if you’ve got an array containing cells with different formats?

  7. on 25 Apr 2009 at 7:52 pm Jonas

    yes, how is it about vectors?

  8. on 07 Dec 2009 at 9:08 am bleu

    thansk a lot..
    those help docs at matlab servers suck…
    everthings so irrelevant

  9. on 11 Jun 2011 at 12:16 am tv

    And how to write one element of array to a single line.
    ex A=[1 2 3 4]
    =>
    1
    2
    3
    4

  10. on 03 Jan 2012 at 5:03 am mehdi

    Hi,
    I have same problem a bit different.
    I have a m-file, I want to delete a special row in it and replace it with another statement through matlab command window ,(for example in my m-file there is p=2; in 7th row, and I want to delete it and replace with p=11.234;).

    What is the easiest and best way to do so?

    Thanks,

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.