CSawy
CSawy

Reputation: 924

matlab read csv file with dates, strings, and numbers

How can I read the following input csv file into matlab.

mid     cid     rate    value    date 
1262    24294   4       ?        7/4/04
1810    18187   3       ?        3/12/04
2000    23573   5       ?        1/20/05
3312    25907   1       ?        5/12/05

I want to have a matrix that has 5 columns [mid, cid, rate, value, date]

NOTE: the "value" column should be -1 instead of the question mark.

I try to use cvsread but it gives an error.

Thanks!

Upvotes: 0

Views: 1107

Answers (1)

Stewie Griffin
Stewie Griffin

Reputation: 14939

Have a look at this answer to this question. I think it does exactly what you want.

You may try textscan and manually convert the date column using datenum

fid = fopen('datafile.csv');
data = textscan(fid, '%f %f %f %s', 'Delimiter', ',', 'HeaderLines', 1);
fclose(f);
data{4} = datenum(data{4});

will return a cell array data of doubles where the fourth column is the MATLAB datenum corresponding to each date, and each other column is the corresponding column from the file.

Using this approach, you will need to read the header line separately. It can easily be done like this:

mid = data{1};   % etc...

You may also read the names from file and use eval to do the assigning, but if the number of columns is small, I recommend avoiding eval.

Upvotes: 2

Related Questions