【问题标题】:How to read files with possible headers in MATLAB?如何在 MATLAB 中读取带有可能标题的文件?
【发布时间】:2018-04-11 14:50:57
【问题描述】:

最初我的文件看起来像:

1.4 2.0
4.2 2.1
5.1 1.2

列号是固定的,而行号因文件而异。以下代码可以读取这些文件:

fid = fopen("my_file.txt","r");
M = fscanf(fid,"%f",[2,inf]);

这里M是数据文件的转置。

现在我得到了几个新文件,其中可能有一个以# 开头的行标题:

# file description
1.0 2.0
1.5 2.2

保证then header不超过一行,且始终以#开头。

我知道我可以逐行读取文件来处理标题。我想知道是否有任何方法可以使我的原始代码尽可能少地更改,以便新代码可以读取两种格式的文件。

textscanf 函数似乎能够处理标题,但字段 Headerlines 的参数是固定数字。

【问题讨论】:

    标签: matlab file-io formatted-input


    【解决方案1】:

    如果您的标题以特定字符为前缀,那么您可以使用textscan'CommentStyle' NV-pair 忽略它们:

    以下test.txt

    # A header line
    1 2
    3 4
    5 6
    

    我们可以使用:

    fID = fopen("test.txt", "r");
    M = textscan(fID, "%f", "CommentStyle", "#");
    M = reshape(M{:}, 2, []).';
    fclose(fID)
    

    这给了我们:

    >> M
    
    M =
    
         1     2
         3     4
         5     6
    

    或者,如果您想坚持使用fscanf,您可以使用fgetl 检查文件的第一行,并在必要时使用frewind(因为fgetl 移动文件指针),返回如果没有标题,则为文件的开头。

    例如:

    fID = fopen("test.txt", "r");
    
    % Test for header
    tline = fgetl(fID);  % Moves file pointer to next line
    commentchar = "#";
    if strcmp(tline(1), commentchar)
        % Header present, read from line 2
        M = fscanf(fID, "%f", [2, inf]).';
    else
        % Header present, rewind to beginning of file & read as before
        frewind(fID);
        M = fscanf(fID, "%f", [2, inf]).';
    end
    fclose(fID);
    

    这给出了与上面相同的结果。如果标题行的数量不是恒定的,您可以使用 ftellfseekwhile 循环跳过过去的标题,但此时您可能会使事情变得比他们真正需要的更复杂用于此应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 2023-03-29
      • 2021-06-01
      • 1970-01-01
      • 2018-02-05
      相关资源
      最近更新 更多