Nov 7, 2008

Export Data from Matlab to Text Files

First eigenfunction of the L-shaped membrane, ...Image via Wikipedia

There are many different ways to export and import data from matlab. You can import and export data from and to matlab binary formats (MAT files), text files, Excel spreadsheet (works only on Windows), XML, several special purpose formats, and a lot of image, audio, and video file formats. Text formats are very useful, because they very portable in that they can be read and written by many different applications.

In this post I will give some examples of exporting to different text formats. I will also mention how to import data using complementary commands.

The simplest way to export data to text format is this:
save -ascii

Matlab exports data by default in the scientific numeric format. If you want to use these data with some other program outside matlab, this can lead to problems. Although nowadays many programs use libraries that permit reading scientific notation (e.g. boost regex library for C++), it is sometimes better to write to a fixed-digits format.

Using save, the -double option says that you want the numbers in 16-digit format.

To write matrix A to a column separated value (CSV) file, there are several alternatives. dlmwrite is one possibility:
>> dlmwrite('attr20.ascii',A,'delimiter',',');

The default delimiter is already the comma, so the last parameter is unnecessary. If you want your data space-separated this command is your friend:
>> dlmwrite('attr20.ascii',A,'delimiter','\t');

If you use the tabulator as delimiter, you can use also use save:

>> save('attr20.ascii','A','-ascii','-double','-tabs');

The last option I give here is csvwrite:
>> csvwrite('attr20.ascii',A); 

These commands work for vectors and two-dimensional matrices.

Also sometimes useful is diary to save your command history to a disk file. You can view and edit the resulting text file using any word processor.

For importing data to matlab you can use the corresponding commands dlmread, load, csvwrite. Some files you might have to filter before reading them into matlab. For example to get rid of comments. Say the files provide comments at the start of the line starting with the percent sign (%). Then filtering can be done with sed:
> sed -i /^%/d *

Enjoy. Please leave a comment below for questions and suggestions.

You might also be interested in my article on exporting figures from matlab. I also wrote an article about creating videos in matlab.

38 comments:

  1. so this is the way to do that, my classmate commented something about this function, but he can't explain so well as you, and for this reason I has been for hours looking for a good answer.

    ReplyDelete
  2. Hi,
    this has worked great but is there anyway to get it to write the values on a new line each time rather than in a long line??

    ReplyDelete
  3. @James: I suppose you want line breaks as delimiters. Try dlmwrite('attr20.ascii',A,'delimiter','\n');

    ReplyDelete
  4. Thank u very much for the article. Could you plz kindly guide me how to change the default format(scientifice notation) in csvwrite()

    ReplyDelete
  5. Hi,
    this has worked great but is there anyway to get it to write the
    values on a new line each time rather than in a long line??

    ReplyDelete
  6. With dlmwrite, try \n or \r as delimiter, for example like this: dlmwrite('attr20.ascii',A,'delimiter',',');

    ReplyDelete
  7. Use the precision argument. For example, if you want to have 10 digits before and 5 digits after the decimal point: dlmwrite('attr20.ascii',A,'precision','%10.5f');

    ReplyDelete
  8. I am very interested by reading this..Its not a common thing to post a such article..I appreciate your blog..Keep posting this type of articles..esire to learn even more issues approximately it!

    ReplyDelete
  9. Nice to read your blog on this website. different experience
    to read this blog. i get some awesome information throw this article.
     

    ReplyDelete
  10. I admire your dedication to
    excellence. Your content is very obviously well-researched. I got so involved
    in your article that I couldn’t even make myself quit reading. Thank you for
    producing such great quality work.

    site: http://exerciseprograms.co/

    ReplyDelete
  11. I’m extremely pleased to read through this original content!
    Your site appeared to be extremely completely unique and possibly a must read!
    Compared with other posts, your site was full of subject matter which is
    fascinating to see! Hope you like my quick remark. Keep publishing!
    Otsingumootori
    optimeerimine

    ReplyDelete
  12. It was amazing visiting your blog. This is kind of different than other blogs. Marietta
    bankruptcy attorney
     emagrecer Idol
    White

    ReplyDelete
  13. hi
    how can i convert the double type data to double type array for using in this order?

    ReplyDelete
  14. Very simple and helpful, Thanks :) Better than mathworks :)

    ReplyDelete
  15. Hi,
    good article by the way I've a problem with the exportation to *.txt file.
    How can I get a *.txt file with columns close to each other. 

    ReplyDelete
  16. I have a large matrix (14692 x 12529). When I export it using csvwrite('file.csv', A) and then import it using the import wizard its values change.  Before I exported it, every element of the first column was unique.  After I imported it, there were only 13803 unique elements out of 14692.  Any ideas how I can fix this or what's going on?  Thanks so much for writing this blog.

    ReplyDelete
  17. Hi I read your article by coincidence :D and I really liked it. Simple and focusing on the subject directly. Do you have any articles about simmechanics? Friction modelling or controlling in simmechanics.

    ReplyDelete
  18. HOW TO SAVE THE SAMPLES OF AUDIO FILE IN TEXT FILE USING MAT LIFE.......?

    ReplyDelete
  19. I've been surfing on-line more than three hours today, but I never discovered any fascinating article like yours. It is pretty worth enough for
    me. Personally,
    if all webmasters and bloggers made excellent content as you did, the net will probably be much
    more useful than ever before.

    Feel free to visit my weblog: BlackPeopleMeet reviews

    ReplyDelete
  20. Hey just wanted to give you a quick heads up.

    The text in your article seem to be running off
    the screen in Internet explorer.
    I'm not sure if this is a formatting issue or something to do with browser compatibility but I figured I'd
    post to let you know. The design look great though! Hope you get the problem resolved soon.


    Many thanks

    my web site; horse stall mats For home gym

    ReplyDelete
  21. Link exchange is nothing else except it
    is only placing the other person's blog link on your page at proper place and other person will also do same in support of you.

    Take a look at my blog - league of legends hack

    ReplyDelete
  22. The Year of Eating Oat Bran also known as hand, herpes zoster foot and mouth disease, as well
    as planted in the Monticello garden.

    Feel free to visit my homepage - Treatment for chickenpox

    ReplyDelete
  23. I used to be able to find good information from your articles.



    Feel free to surf to my blog :: Code psn gratuit

    ReplyDelete
  24. I'm really loving the theme/design of your website. Do you ever run into any browser compatibility problems? A small number of my blog visitors have complained about my website not operating correctly in Explorer but looks great in Firefox. Do you have any tips to help fix this issue?

    Also visit my web site Money

    ReplyDelete
  25. One problem I have that I want to export x,y,z coordinates of different slices matlab makes for me. The problem though is in the exported .txt files they are not in nice columns but per 3 and then seperated by a tab. This is what i have done:

    dlmwrite (['stuk_' int2str(i) '.txt'],P,'\t')



    With P being horzcat (-X,Y,Z), with xyz depending on (i) in a for loop.
    So what i want to obtain is for each file to have something like this
    X

    ReplyDelete
  26. waermepumpentrockner test
    This is a topic which is close to my heart... Take care!
    Exactly where are your contact details though?

    waermepumpentrockner test

    ReplyDelete
  27. While many realized tutors get abandoned desire associated with actually discovering the truth at the rear of clash of clans hack, We for starters think that it is however a new worthy result in with regard to exam.
    Underrate clash of clans hack pictures peril. Although it is now a warm
    matter with regard to discussion, it's have
    an effect on with american movie theatre is not presented correct acknowledgement.
    Generally it's viewed as equally any guide and also a hinderence towards the aristocracy, captured through their
    particular well known historical past. Trying to keep doing this as the primary goal, within this dissertation Let me examine the particular key troubles.


    Community can be a people product or service. As soon as M L Darcy claimed 'fevour may spread' the lady discovered obviously
    into the individual coronary heart. A lot has been claimed regarding the impact in the press on clash of clans hack.
    Observers state it illustrates a coherent tactic, something and so lacking in our lifestyle, that it's certainly not identified by just
    about all.

    Involving extremely important magnitude in order to any kind
    of analyze connected with clash of clans hack inside it's circumstance, will be understanding
    the particular attitudes connected with contemporary society.
    It is intrinsically connected to teenagers interior acclimatization.
    The actual figures make it clear that will clash of clans
    hack can be a major industry element. Effectively acrylic costs looms in excess of clash
    of clans hack this are not some sort of coincidence.

    Assumptions manufactured by investors have got brought about uncertainty on the
    list of private sector. State policies has in
    certain areas been recently observed to grasp an escalating antithesis involving intergovernmental resulting in neo-functionalism.
    Contrasting recent politics idea achievable held just 10 years in the
    past is compared to contrasting pre and also publish conflict opinions regarding clash of clans hack.

    ReplyDelete
  28. Hi colleagues, its great article on the topic of educationand completely explained, keep it up all the
    time.

    Have a look at my webpage - discount sunglasses

    ReplyDelete
  29. Hi thiѕ iѕ kind of of off topic but I was wanting
    to know if blogs use WYSIWYG еditors or if you ɦave to manually code ѡith
    HTМL. I'm starting a blog soon but have no coding know-how so I wanteɗ tо get adviсe from someone with exрerience.
    Any help would be greatly appreciatеd!

    Check out my page derm exclusive anti aging system

    ReplyDelete
  30. Hi, I log on to your blog daily. Your humoristic style is witty, keep
    it up!

    My homepage - compagnie déménagement

    ReplyDelete
  31. On the other hand, if you are ordering from some other country, then you are asked to wait for
    4 to 21 days depending upon the reach of Canadian pharmacies.
    Of the patients can be diagnosed conditions in the comfort of their homes.
    Problems of time shortage and gradually increase in drug costs are best solved by making
    a contact to any legitimate online pharmacy.

    my web-site: traitement pour l allergie - twitter.com,

    ReplyDelete
  32. told her that she hadn��t been able to finish it. Simpson told her she would like the ending. Over the years Lisa had an on-and-off relationship with Simpson, but it would be closer in Louis Vuitton Outlet Handbags some ways than the one she had with her father.

    ReplyDelete