用 MATLAB 读取 CSV 文件? [英] Reading CSV files with MATLAB?
问题描述
我正在尝试使用 MATLAB 读取 .csv 文件.这是我的代码:
I am trying to read in a .csv file with MATLAB. Here is my code:
csvread('out2.csv')
这是 out2.csv 的样子:
This is what out2.csv looks like:
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
在 Windows 上,我可以使用 xlsread 函数读取这个完全相同的文件,没有任何问题.我目前在一台 linux 机器上.当我第一次使用 xlsread 读取文件时,我被告知文件不是可识别的格式",所以我改用 csvread.但是,使用 csvread,我收到以下错误消息:
On windows I am able to read this exact same file with the xlsread function with no problems. I am currently on a linux machine. When I first used xlsread to read the file I was told "File is not in recognized format" so I switched to using csvread. However, using csvread, I get the following error message:
Error using dlmread (line 139)
Mismatch between file and format string.
Trouble reading number from file (row 1u, field 2u) ==> /09/2013
23:55:12,129.32,129.33
Error in csvread (line 48)
m=dlmread(filename, ',', r, c)
我认为日期中的/"是导致问题的原因.在 Windows 上,第一列被解释为字符串.在 linux 上,它似乎被解释为一个数字,因此它尝试读取该数字并在反斜杠处失败.这就是我认为至少正在发生的事情.任何帮助将不胜感激.
I think the '/' in the date is causing the issue. On windows, the 1st column is interpreted as a string. On linux it seems to be interpreted as a number, so it tries to read the number and fails at the backslash. This is what I think is going on at least. Any help would be really appreciated.
推荐答案
csvread
只能读取双打,所以在日期字段卡住了.使用 textscan
.
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};
<小时>
更新(8/31/2017)
自从 2013 年写回,MATLAB 的 textscan
函数已更新为直接读取日期和时间.现在代码看起来像这样:
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{:});
下面@Victor Hugo 提到的另一种选择(目前我个人对这种情况的首选)是使用 readtable
它将接受与 textscan
相同的格式化字符串,但将结果直接组合成一个表格对象:
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
这篇关于用 MATLAB 读取 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!