【问题标题】:Matlab: reading rows of different formats from csv fileMatlab:从csv文件中读取不同格式的行
【发布时间】:2013-05-18 21:00:42
【问题描述】:

我正在尝试读取包含以下格式数据的 csv 文件:

02/01/2012  03/01/2012  04/01/2012  05/01/2012  06/01/2012 09/01/2012 10/01/2012
1w  0.652   0.626   0.606   0.584   0.564   0.546   0.53
2w  0.738   0.716   0.7 0.68    0.662   0.645   0.628
3w  0.845   0.826   0.808   0.785   0.762   0.746   0.734
1m  1.005   0.988   0.97    0.951   0.93    0.912   0.894
2m  1.165   1.152   1.137   1.122   1.105   1.092   1.083
3m  1.343   1.333   1.319   1.303   1.288   1.276   1.267
4m  1.425   1.416   1.403   1.387   1.372   1.362   1.355

我已阅读以下帖子: How to use "csvread" when the contents in the file have different formats?

Reading date and time from CSV file in MATLAB

但我仍然无法弄清楚如何读取包含表示日期的字符串的第一行并将其转换为 matlab 日期格式。

【问题讨论】:

标签: matlab datetime csv file-io


【解决方案1】:

尝试以下方法:

%# open file for reading
fid = fopen('file.csv', 'rt');

%# read first line and extract date strings
dt = textscan(fgetl(fid), '%s');

%# read the rest of the data
D = textscan(fid, '%s %f %f %f %f %f %f %f', 'CollectOutput',1);

%# close file
fclose(fid);

%# convert to serial date numbers
dt = datenum(dt{1}, 'mm/dd/yyyy')

%# place data in individual cells
D = [D{1} num2cell(D{2})]

结果:

dt =
      734900
      734929
      734960
      734990
      735021
      735113
      735143
D = 
    '1w'    [0.652]    [0.626]    [0.606]    [0.584]    [0.564]    [0.546]    [ 0.53]
    '2w'    [0.738]    [0.716]    [  0.7]    [ 0.68]    [0.662]    [0.645]    [0.628]
    '3w'    [0.845]    [0.826]    [0.808]    [0.785]    [0.762]    [0.746]    [0.734]
    '1m'    [1.005]    [0.988]    [ 0.97]    [0.951]    [ 0.93]    [0.912]    [0.894]
    '2m'    [1.165]    [1.152]    [1.137]    [1.122]    [1.105]    [1.092]    [1.083]
    '3m'    [1.343]    [1.333]    [1.319]    [1.303]    [1.288]    [1.276]    [1.267]
    '4m'    [1.425]    [1.416]    [1.403]    [1.387]    [1.372]    [1.362]    [1.355]

【讨论】:

  • 酷。我不得不稍微修改它(添加“分隔符”等),但我明白了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 2021-02-11
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多