【问题标题】:formatted read from matlab using fscanf使用 fscanf 从 matlab 格式化读取
【发布时间】:2015-09-02 15:15:09
【问题描述】:

我有一个格式如下的文本文件:

Row: 001, rank: 6, max: 0.2431, index: 15.

Row: 002, rank: 10, max: 0.2331, index: 1.

Row: 003, rank: 110, max: 0.2330, index: 10.

也就是说,字段row 用零填充,因此数字具有三位。字段max 也被填充,使其具有固定长度。 rankindex 都没有填充。

[编辑本帖后添加]此外,数据前面有几行不相关的文本。不相关文本的行数未知。当且仅当它低于该行时,该行的格式如上:DATA START BELOW

有没有办法使用命令读取文件

[A, count] = fscanf(fid,['what is a proper format?'],[?, numberOfRows]);

A = A';B = A(:,[i,j,k,l]);

这样B=[1,6,0.2431,15; 2,10,0.2331,1; 3,110,0.2330,10;];?

我知道的一种方法是[A, count] = fscanf(fid,['%s %d, %s %d, %s %f, %s %d.'],[AnInstantNumberRelatedToTheLengthOfALine, numberOfRows]); 但是,当新字段附加到每一行时,这种方法似乎缺乏灵活性。

【问题讨论】:

    标签: string matlab file-io formatting scanf


    【解决方案1】:

    这是一种方法:

    s = importdata('file.txt'); %// read file as cell array of strings; one line per string
    s = [s{:}]; %// concatenate into a single string
    ind = regexp(s, 'DATA START BELOW', 'end'); %// locate line that marks start of data
    s = s(ind+1:end); %// keep only data
    s = regexp(s, '-?\d+\.?\d*', 'match'); %// extract numbers as a cell array of strings
    s = str2double(s); %// convert to numbers 
    s = reshape(s.', 4, []).'; %// reshape into four columns in row-mayor order
    

    【讨论】:

    • 感谢您的回复。我忘了提到数据之前可能有几行(行数不同)。 Data Start Here 行下方的所有数据均有效。有什么办法可以处理吗?我尝试了您的方法,但它显示“来自非单元格数组对象的单元格内容引用”。对于命令s=[s{:}];.
    • 请编辑问题中的示例以反映文件的确切格式
    • 请查看编辑后的答案。我添加了两行来处理这个
    【解决方案2】:

    另一个答案:

    fileID = fopen('mydata.txt');
    C = textscan(fileID,'%s %f %s %f %s %f %s %f','delimiter',{',','Row:','max:','rank:','index:'});
    fclose(fileID);
    C = C(2:2:8);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多