MATLAB: How to import multiple CSV files with mixed data types

13,178

What you're looking for is maybe the function xlsread.

It opens any file recognized by Excel, and automatically separates text data from numerical data.

The problem is that the default delimiter for at least on my computer is ;, and not , (at least for my locale here in Brazil). So xlsread will try to separate the fields on the file with a ;, and not a comma as you'd like.

To change that you have to change your system locales to add the comma as the list separator. So if you feel like it, to do it in windows vista, click Start, Control Panel, Regional and Language Options, Customize this format, and change the List Separator from ';' to ','. On other windows the process should be almost the same.

After doing that, typing:

[num, txt, all] = xlsread('your_file.csv');

will return something like:

num =

10
300


txt = 

'01/01/2012'    ' 00020.x1'
'02/01/2012'    ' 00203.x1'


all = 

'01/01/2012'    ' 00020.x1'    [ 10]
'02/01/2012'    ' 00203.x1'    [300]

Notice that if your locale has already the list separator set to ',', you won't have to change anything on your system to make that work.

If you don't want to change your system just to use the xlsread function, then you could use the textscan function described here: http://www.mathworks.com/help/techdoc/ref/textscan.html

The problem is that it is not as simple as calling it, as you will have to open the file, iterate on the lines, and tell matlab explicitly the format of your file.

Best regards

Share:
13,178
user1205030
Author by

user1205030

Updated on June 04, 2022

Comments

  • user1205030
    user1205030 almost 2 years

    I have just started learning MATLAB and have difficulties to import csv files to a 2-D array..

    Here is a sample csv for my needs:(all the csv files are in the same format with fixed columns)

    Date,                Code,         Number....
    2012/1/1,            00020.x1,             10
    2012/1/2,            00203.x1,            0300
    ...
    

    As csvread() only works with integer numbers, should I import numeric data and text data separately or is there any quick way to import multiple csv files with mixed data types?

    Thanks a lot!!