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.

70 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
  33. Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this field.
    pacman |happy wheels |my little pony games | unblocked games
    friv4 kizi 4| unblockedgames

    ReplyDelete
  34. hi..just wanna ask you something regarding my matlab project. You know,I want to copy the variable which contains the pixels of the image(which is a map) into a .txt file.But the problem is,I dont know how. I've been trying to find in the internet but I dont understand single of them,i mean none of them answers my question.Can u please answer my question?

    ReplyDelete
  35. Thank you so much for this article. I've been finding it :) It will helps me much. I hope to see more and more posts of yours in the future :)
    happy wheels hacked | car games | racing games | online games | starcraft | starcraft html5 | starcraft online | starcraft web

    ReplyDelete
  36. Oh. good to be here in your article or post, whatever, I think I should also work hard for my own website like I see some good and updated working in your site
    happy wheels
    super mario bros
    pacman
    agario

    ReplyDelete
  37. SBI Specialist Officer Notification 2015-16 Eligibility Criteria


    This is my first time visit on your site and i have bookmark this for again visit. thanks a lot of for sharing appreciable post ................

    ReplyDelete
  38. Thank you for the information you provide, i like camera b612 | download camera b612 | camera b612 | download b612 | download camera b612 | B612 | download camera b612 | b612 | download camera b612 | papa games | Papas Games | papa's games | Dream League Soccer | Score Hero | Dream League Soccer | Score Hero game | Score Hero. How about you? B612 is perfect for taking selfies anytime, anywhere. B612 is a photography app specially designed for selfies that lets you apply dozens of filters to your images before sharing them through your favorite social networks.
    Free Games Online | free games | free online games | Free Games Online | free games

    ReplyDelete
  39. I found a lot of information here to create this actually best for all newbie here. Thank you for this information.
    happy wheels , super smash flash 2 , happywheel

    ReplyDelete
  40. Who will ever believe that a herb can cure 12 years HIV in my body, My name is Williams Morgan, I never believe that it will work that is why am dropping this post. I have spent a lot getting drugs from the hospital to keep me healthy, what i was waiting for was death because I was broke. One day a friend of mine from UK came to visit me and saw my condition was getting worst, then she told me about this great man from African called professor oseamuyi who cured her sister from HIV and cancer of the breast, without demanding much from her, she told me that he is well known in curing HIV/AIDS, HERPES (HSV1, HSV2), (HPV) ACUTE RETROVIRAL SYNDROME (ARS), CANCER, VITILIGO, DIABETES, HEPATITIS B. CANCER, CELIAC, CHLAMYDIA, STROKE and any kind of Deadly DISEASES ,BLOOD DISEASE,DIABETES,TYPHOID I decided to email him, unknowingly to me that this will be the end of the HIV aids in my body, he prepare for me Herbs and prescription on how to take it, at the end of three weeks, i was asked to go to the hospital for a checkup, and i went, Surprisingly after the test the doctor confirm me negative, i thought it was a joke, i went to another hospital, it was also negative, I was so happy that I quickly introduce my friend who has been suffering from Herpes for the past 5 years to professor oseamuyi, after taking the Herbs professor oseamuyi send to her, less than four days the inching and pains stop, less than 3 weeks she was completely heal and healthy again. Words alone cannot express how much joy and happiness i have now... Please I want everyone out there with any virus or infection to be healed and healthy, Health is Wealth. Contact professor oseamuyi on:professoroseamuyi@yahoo.com for he is indeed a great man. you can also contact me on my email:williamsmorgan621@gmail.com

    ReplyDelete
  41. I love all the posts, I really enjoyed, I would like more information about this, because it is very nice., Thanks for sharing.
    monkey go happy | monkey go happy 2 | learn to fly | learn to fly 3 | pacman |  pacman game | mahjong |  mahjong games | cat mario 4 | cat mario | happy wheels | happy wheels game

    ReplyDelete
  42. Medical scientists have discovered a new way to battle HERPES by using a man called Dr. Lamano
    MY NAME IS Michael Storm Willie.I SAW A COMMENT ON POSITIVE BLOGS AND I WILL LOVE TO TELL EVERY BODY HOW MY STATUS CHANGES TO NEGATIVE amd i got cured,
    AND AM NOW A LIVING WITNESS OF IT AND I THINK ITS A SHAME ON ME IF I DON'T SHARE THIS LOVELY STORY WITH OTHER PEOPLE INFECTED WITH THIS DEADLY VIRUS.
    HERPES HAS BEEN ONGOING IN MY FAMILY, I LOST BOTH PARENTS TO HERPES. AND IT IS SO MUCH PAIN I'VE NOT BEEN ABLE TO GET OVER..
    AS WE ALL KNOW MEDICALLY THERE IS NO SOLUTION TO IT..AND MEDICATION IS VERY EXPENSIVE..SO SOMEONE INTRODUCED ME TO A HERBAL PRACTITIONER IN AFRICA..
    I HAD A JOB THERE TO EXECUTE SO I TOOK TIME TO CHECK OUT ON HIM.I SHOWED HIM ALL MY TESTS AND RESULTS..
    I WAS ALREADY DISORGANIZED WITH HERPES AND IT WAS ALREADY TAKING ITS TOWL ON ME..
    I HAD SPENT THOUSANDS OF DOLLARS SO I DECIDED TO TRY HIM OUT ALTHOUGH I DID'NT BELIEVE IN IT,
    I WAS JUST TRYING IT OUT OF FRUSTRATION? AND AFTER 6 DAYS, HE TOLD ME TO GO FOR A MEDICAL TEST.
    AND YOU WON'T BELIEVE THAT 5 DIFFERENT DOCTORS CONFIRMED IT THAT AM NEGATIVE..IT WAS LIKE A DREAM,,I NEVER BELIEVE HERPES HAS CURE..AM NOW NEGATIVE,,
    AM A LIVING WITNESS..I DON'T KNOW HOW TO THANK THIS MAN? I JUST WANT TO HELP OTHERS IN ANY WAY I CAN..
    I HAVE JOINED MANY FORUMS AND HAVE POSTED THIS TESTIMONIES AND ALOT OF PEOPLE HAS MAIL AND CALLED THIS MAN ON PHONE AND AFTER 6 DAYS THEY ALL CONFIRMED NEGATIVE..
    BBC NEWS TOOK IT LIVE AND EVERY EVERYBODY SAW IT AND ITS NOW OUT IN PAPERS AND MAGAZINES THAT THERE IS A HERBAL CURE FOR HERPES AND ALL WITH THE HELP OF THIS MAN,,
    IF YOU WISH TAKE IT OR NOT..GOD KNOWS I HAVE TRIED MY BEST. ABOUT 28 PEOPLE HAVE BEEN CONFIRMED NEGATIVE THROUGH THE HERBAL CURE OF DR.LAMANO.
    AND THEY SEND MAILS TO THANKS ME AFTER THEY HAVE BEEN CONFIRMED NEGATIVE,,THIS MAN IS REAL..DON'T MISS THIS CHANCE,,HERPES IS A DEADLY VIRUS,,GET RID OF IT NOW..
    If there is anyone who has similar problem and still looking for a way out, his email still remains lamanospellalter@yahoo.com or call him on +2349054870144 whatsapp also +2349054870144
    Thanks Moderators

    ReplyDelete
  43. Platos maravillosos, Gracias por compartir, creo que es muy interesante. Usted también puede unirse a los juegos más recientes de nuestro disfrutar de la diversión que habíamos traído. Gracias.
    Juegos de Matar Zombies
    earn to die
    earn to die 2
    earn to die 3
    earn to die 4
    earn to die 1
    earn to die part 2
    earn to die 5
    earn to die 6

    ReplyDelete
  44. Posts shared useful information and meaningful life, I'm glad to be reading this article and hope to soon learn the next article. thank you
    agario
    happy wheels
    car games
    pacman
    plants vs zombies
    solitaire

    ReplyDelete
  45. I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again..
    cool games| cool math games| 8 ball pool| sudoku| yoob| stickman games| unblocked games | shooting games| friv4school|
    happy wheels| fighting games

    ReplyDelete
  46. Unfortunately many of us will fail because we just get lost in all the information and aspects of running an online business. There are countless ways too make money online but there is a lot to learn as well.

    ReplyDelete
  47. Nicely written information in this post, the quality of content is fine and picture very nice. Things are very open and intensely clear explanation of issues.
    play run 3 | head football | free online mahjong |

    ReplyDelete
  48. Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic.
    Signature:
    Download retrica online includes more than eighty different filters with many different styles and include retrica indir , and zombie tsunami is the ideal game for anyone who loves the running game genre

    ReplyDelete