【问题标题】:Reading complicated format CSV fileinto Matlab将复杂格式的 CSV 文件读入 Matlab
【发布时间】:2012-05-21 20:01:11
【问题描述】:

我的原始 CSV 文件看起来像第一张照片。我想用 Matlab 把它读成第二张图片的格式。我有超过 1000 个相同类型的 CSV 文件,如果我通过复制/粘贴来做会很痛苦。我怎样才能做到这一点?有什么例子吗?

原始数据:

输出数据:

【问题讨论】:

    标签: matlab csv file-io input import-from-csv


    【解决方案1】:

    首先要意识到 .csv 文件的格式非常简单。您上面的文件实际上是一个纯文本文件,每行包含以下文本:

    id,A001
    height
    a1,a2,a3
    3,4,5
    3,4,5
    6,7,5
    
    weight
    a1,a2,a3
    4,4,5
    5,4,6
    i6,7,5
    

    因此,在 Matlab 中编写自己的解析器并不难。你想使用类似的命令

    fid = fopen('filename.csv','r');
    L = fgetl(fid); % get a text line from the file
    commas = find(L==','); % find where the commas are in the line
    n1 = str2num(L(1:commas(1)-1); % convert the first comma-delimited number on line L
    fidout - fopen('myfile.csv','w');
    Lout =  [ L(commas(2)+1:commas(3)-1) ', a1, a1'];
    fwrite(fidout,Lout); % write a line out to the output file
    fclose all; % close all open files.
    

    首先将各种值读取到各种变量中,然后按照您希望将它们写入输出文件的方式排列它们,看起来会很慢。但是一旦你开始滚动它会很快,你会发现自己对文件中的内容有很好的理解,并且你会亲身了解编写texscan.mcsvwrite.m等内容所涉及的内容。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 2013-10-31
      • 2013-12-13
      相关资源
      最近更新 更多