MATLAB: How to import multiple CSV files with mixe

2019-05-26 10:07发布

问题:

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!!

回答1:

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



回答2:

I recently wrote a function that solves exactly this problem. See delimread.

It's worth noting that xlsread on csv files only works in windows. On Linux or Mac, xlsread works in 'basic' mode which cannot read csv files. It might not be a great idea in the longrun to use xlsread in case you need to migrate across platforms or automate code runs on Linux servers.

xlsread is also much slower than other text parsing functions since it opens an Excel session to read the file.