Reading text data from a CSV file in MATLAB

Nishant picture Nishant · Jul 20, 2011 · Viewed 7.3k times · Source

my data is in following form:

days of week      date        time(hrs)        visitors
mon            jan 2 2010     900               501 
mon            jan 2 2010    1000               449
mon            jan 2 2010    1100               612

likewise for every day for entire year. i need to create a matrix of days of week as shown below:

A=[
    mon
    mon
    mon
]

Answer

Amro picture Amro · Jul 20, 2011

Here is how I would read the tab-separated values, and parse the dates:

%# read and parse file
fid = fopen('data.csv','rt');
C = textscan(fid, '%s %s %s %d', 'Delimiter','\t', 'HeaderLines',1, ...
    'MultipleDelimsAsOne',true, 'CollectOutput',false);
fclose(fid);

%# get date and number of visitors
dt = datenum(strcat(C{2}, {' '}, C{3}), 'mmm dd yyyy HHMM');
visitors = C{4};

%# plot
plot(dt,visitors)
datetick('x')
xlabel('time of day'), ylabel('visitors')

enter image description here

As for the day-of-week column, you can get it as:

>> C{1}                        %# first column from file
ans = 
    'mon'
    'mon'
    'mon'

>> cellstr(datestr(dt,'ddd'))  %# actual day of week from parsed dates
ans = 
    'Sat'
    'Sat'
    'Sat'

this produces different days (either your data posted was simply made-up, or you have a bug in the part that generated those dates!)