【问题标题】:Matlab reading text issueMatlab阅读文本问题
【发布时间】:2014-12-03 14:32:25
【问题描述】:

我正在尝试将一种结构化文本文件读入 MatLab。内容如下:

 Header

 Result  Damage  "Load Analysis"      0.002000000    Vector    OnNodes
ComponentNames "DN", "DT"
Values
    1  0.00000000E+00  0.00000000E+00
    2  0.00000000E+00  0.00000000E+00
    3  0.00000000E+00  0.00000000E+00
    4  0.00000000E+00  0.00000000E+00
End Values

 Result  Damage  "Load Analysis"      0.004000000    Vector    OnNodes
ComponentNames "DN", "DT"
Values
    1  0.00000000E+00  0.00000000E+00
    2  0.00000000E+00  0.00000000E+00
    3  0.00000000E+00  0.00000000E+00
    4  0.00000000E+00  0.00000000E+00
End Values

这些值会以块的形式不断重复。对于文件中的每个块,我只需要从重复块内的行中读取这 3 个值。我想到了这样的代码:

fid=fopen('FileName.res');
while ~feof(fid)
    tline = fgetl(fid);
    if ischar(strtrim(tline)) == 1
        continue
    else
    %command to put the values within a matrix of kind A[inf,3]
    end
end

第一个问题是,当涉及到实际是数字的行时,命令 ischar 返回 1 作为值。这样我仍然无法进入将数字放入矩阵的第二部分。关于这些问题有什么想法吗?

【问题讨论】:

  • fgetl 的输出总是一个字符数组,除非该行只包含一个换行符。一个建议是调整你的逻辑,而不是寻找“价值”并阅读,直到看到“最终价值”

标签: matlab io


【解决方案1】:

如果您的文件具有一致的格式,我会查看 textscan,因为它非常灵活,并且非常适合带有像您这样的块的文件。

否则,对于尽可能接近原始代码的解决方案,只需尝试将每一行读取为一个数字,如果成功,请将数字添加到您的表格中,如果失败,请继续下一行。

fid=fopen('FileName.res');
fullTable = [] ;
while ~feof(fid)
    tline = fgetl(fid);
    tempRow = sscanf( tline , '%d%f%f' ).' ; %' // try to read the string as numbers
    if ~isempty(tempRow)
        fullTable = [ fullTable ; tempRow ] ; % // append numbers to the master table
    end
end
fclose(fid)

【讨论】:

    【解决方案2】:

    问题是fgetl 只是将整行作为字符串读取。即ischar('1 2 3') 返回真。它可能包含数字,但变量类型本身是一个字符串。所以你需要看的不是fgetl返回的类型,而是内容。

    未经测试,但我认为这会起作用:

    fid=fopen('FileName.res');
    while ~feof(fid)
        tline = fgetl(fid);
        if strcmp(tline,'Values')
           tline = fgetl(fid); % this should read the line starting 1
           while strncmp(tline,'End',3) %only match first three letters
             % put values in matrix
             tline = fgetl(fid); % get next line
           end
        end
    end
    

    这应该怎么做:

    1) 读取行,直到找到读取“值”的行(如果还读入了该空格,则可能必须使用 strcmp/strncmp)。
    2) 阅读下一行
    3) 将值放入矩阵
    4) 阅读下一行
    5) 如果下一行不是以“End”开头,则返回 3.
    6)如果下一行确实开始'End',则返回1。

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2011-02-04
      • 1970-01-01
      相关资源
      最近更新 更多