【问题标题】:Reading text data from a CSV file in MATLAB在 MATLAB 中从 CSV 文件中读取文本数据
【发布时间】:2011-07-20 09:22:21
【问题描述】:

我的数据格式如下:

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

全年的每一天也是如此。 我需要创建一个星期几的矩阵,如下所示:

A=[
    mon
    mon
    mon
]

【问题讨论】:

  • 顺便说一句,2010 年 1 月 2 日是星期六 :)

标签: matlab file-io csv data-import


【解决方案1】:

这是我如何读取 制表符分隔值,并解析日期:

%# 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')

至于星期几列,你可以得到它:

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

这会产生不同的日期(要么您发布的数据只是虚构的,要么您在生成这些日期的部分中存在错误!)

【讨论】:

  • 据我所知,如果我的字符串包含 \n ,这仍然会失败。当从 Excel 导出到 csv 并且单元格包含内部换行符时,可能会发生这种情况。
  • @CarlWitthoft 这很棘手,字段值本身的新行......是否引用了字段?也许查看%q 说明符而不是%s
  • 顺便说一句,您是指文字字符串 \n 还是实际的新行(即 LF/CRLF)?
  • 换行符。如果您使用换行符的 - 方法在 Excel 中编写一些多行文本,然后导出为 CSV 并在一些体面的文本编辑器中打开,您可以看到这一点。
  • @CarlWitthoft 好吧,我刚试过,%q 说明符有效。这是我的示例:pastebin.com/Nwd8Vcwx。诀窍是,如果字段中有换行符,则必须用引号引起来(这是 Excel 默认所做的)。
【解决方案2】:

接受this previous question的提示,

fid = fopen('filename.txt');
% Skip a line for the header
s = fgetl(fid);
% Read the rest into data
data = textscan(fid, '%s %s %d %d %d %d');
% Close the file
fclose(fid);

星期几在data 的第一个单元格中。

【讨论】:

    【解决方案3】:

    您可以从 File Exchange 下载我的csvimport 提交。假设您的数据是制表符分隔的,您可以使用以下方式读取它:

    [days datecol timecol visitors] = csvimport( 'file.txt', 'delimiter', '\t', ...
           'columns', {'days of week', 'date', 'time(hrs)', 'visitors'} );
    

    前 2 个输出参数将是字符串元胞数组,而后 2 个将是双精度矩阵。

    【讨论】:

      【解决方案4】:

      如果您刚刚开始使用(最新版本的)matlab,最简单的方法是使用“导入向导”。

      几个简单的步骤:

      1. 浏览到您的文件并右键单击它
      2. 选择要导入的选项
      3. 选择将事物存储为cell array 的选项(向量或矩阵不起作用)。
      4. 点击导入

      您可以选择单击下一步导入并选择要为此过程生成代码。但是,这可能有点冗长。如果你只需要做一次,我会推荐这种方法。

      【讨论】:

        【解决方案5】:

        您可以尝试使用dlmread。它可以采用任何 ASCII 分隔符。我认为它可能适合您的要求。见here

        【讨论】:

          猜你喜欢
          • 2017-05-15
          • 2013-09-12
          • 1970-01-01
          • 1970-01-01
          • 2014-01-07
          • 2019-09-17
          • 1970-01-01
          相关资源
          最近更新 更多