【问题标题】:Read mixed text file in MATLAB在 MATLAB 中读取混合文本文件
【发布时间】:2017-03-28 17:27:45
【问题描述】:

我有一个包含数字和字符的文本文件,更重要的是,它还有*,表示重复。例如:

data
-- comment
34*0.00 0.454 0.223 
0.544 5*4.866 
/

上面的例子以34、zeros、0.00开头,然后是0.454,然后是0.223,然后是0.544和4.866的5重复。这意味着它具有34 + 1 + 1 +1 + 5 = 42 数值。编写可以读取此类文本文件的通用代码的最佳方法是什么?文本文件中的其他内容都不重要;只有数字是相关的。

【问题讨论】:

    标签: string matlab text filereader


    【解决方案1】:

    第一步是读取数据。我假设您的文件内容如下所示:

    -- comment
    34*0.00 0.454 0.223 
    0.544 5*4.866 
    

    对于该格式,您可以像这样使用textscan:

    fid = fopen('data.txt');
    data = textscan(fid, '%s', 'CommentStyle', '--');
    fclose(fid);
    data = data{1};
    

    而data 在显示时将如下所示:

    data =
    
      5×1 cell array
    
        '34*0.00'
        '0.454'
        '0.223'
        '0.544'
        '5*4.866'
    

    现在,您可以尝试几种不同的方法将其转换为所需格式的数字数据。一种(可能是可怕的)方法是像这样使用regexprep:

    >> data = regexprep(data, '([\d\.]+)\*([\d\.]+)', ...
                        '${repmat([$2 blanks(1)], 1, str2num($1))}')
    
    data =
    
      5×1 cell array
    
        '0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0…'
        '0.454'
        '0.223'
        '0.544'
        '4.866 4.866 4.866 4.866 4.866 '
    

    如您所见,它会根据需要复制每个字符串。现在,我们可以使用cellfun 和str2num 将元胞数组的每个元胞转换为数值并将它们连接在一起:

    >> num = cellfun(@str2num, data, 'UniformOutput', false);
    >> num = [num{:}]
    
    num =
    
      Columns 1 through 14
    
             0         0         0         0         0         0         0         0         0         0         0         0         0         0
    
      Columns 15 through 28
    
             0         0         0         0         0         0         0         0         0         0         0         0         0         0
    
      Columns 29 through 42
    
             0         0         0         0         0         0    0.4540    0.2230    0.5440    4.8660    4.8660    4.8660    4.8660    4.8660
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多