Reading CSV files with MATLAB?
csvread
can only read doubles, so it's choking on the date field. Use textscan
.
fid = fopen('out2.csv');
out = textscan(fid,'%s%f%f','delimiter',',');
fclose(fid);
date = datevec(out{1});
col1 = out{2};
col2 = out{3};
Update (8/31/2017)
Since this was written back in 2013, MATLAB's textscan
function has been updated to directly read dates and times. Now the code would look like this:
fid = fopen('out2.csv');
out = textscan(fid, '%{MM/dd/uu HH:mm:ss}D%f%f', 'delimiter', ',');
fclose(fid)
[date, col1, col2] = deal(out{:});
An alternative as mentioned by @Victor Hugo below (and currently my personal go-to for this type of situation) would be to use readtable
which will accept the same formatting string as textscan
but assemble the results directly into a table object:
dataTable = readtable('out2.csv', 'Format', '%{MM/dd/uu HH:mm:ss}D%f%f')
dataTable.Properties.VariableNames = {'date', 'col1', 'col2'};
dataTable =
3×3 table
date col1 col2
___________________ ______ ______
03/09/2013 23:55:12 129.32 129.33
03/09/2013 23:55:52 129.32 129.33
03/09/2013 23:56:02 129.32 129.33
You can use readtable
, as it will accept any input.
https://www.mathworks.com/help/matlab/ref/readtable.html
Unfortunately, the documentation for csvread
clearly states:
M = csvread(filename)
reads a comma-separated value formatted file,filename
. The file can only contain numeric values.
Since /
is neither a comma, nor a numeric value, it produces an error.