【问题标题】:Matlab: How to read and extract matrix by specifying header name?Matlab:如何通过指定标题名称来读取和提取矩阵?
【发布时间】:2017-02-14 18:39:08
【问题描述】:

是否可以从文本文件中读取指定标题下的矩阵? 我有一个这样的文本文件:

Header A (2x3):
3 6 7
5 8 8
Header B (4x4):
23 65 2 6 
4 6 7 8
33 7 8 9

所以我想要完成的是将标题名称作为参数并获取它下面的矩阵。可以用matlab做吗?

提前致谢!!

【问题讨论】:

  • 这些是 5 个数字:2365267。你想在这里生成什么B 矩阵?
  • 哎呀srry,假设只有4个
  • 如果是相应格式的csv文件肯定会更容易。例如。 Header A, Header B\n [3 6 7; 5 8 8], [23 65 2 6; 4 6 7 8; 33 7 8 9]\n。或者更好的是,采用 JSON 格式:stackoverflow.com/questions/26787245/…

标签: matlab matrix text-files


【解决方案1】:

以下方法可行,但如果您要处理大量数据,则可能不会那么快:

function [ matrixOut ] = readLineBasedOnHeader( headerString, FileName )

%readLineBasedOnHeader: Scan through a text file, and return matrix below
% a row which starts with the string `headerString`

% Read each row into cell array:
cellStrings = dataread('file', FileName, '%s', 'delimiter', '\n'); %#ok<DDTRD>

% Find the row matching headerString
headerIndex = ismember(cellStrings, headerString);

if sum(headerIndex) == 1
    % We've found 1 match; return the matrix
    % find how many rows have numberic
    rowIdx = find(headerIndex)+1;
    matrixOut = str2num(cellStrings{rowIdx});       %#ok<ST2NM>
    stillAnumber = ~isempty(matrixOut);

    if ~stillAnumber
        error('row beneath header found not numeric');
    end

    while stillAnumber && rowIdx < length(cellStrings)
        rowIdx = rowIdx+1;
        nextRow = str2num(cellStrings{rowIdx});     %#ok<ST2NM>
        stillAnumber = ~isempty(nextRow);
        matrixOut = [matrixOut; nextRow];           %#ok<AGROW>
    end

elseif sum(headerIndex) > 1
    % More than 1 match; throw an error
    error('More than 1 copy of header string found');

else % Less than 1 match; throw an error
    error('Header string not found');
end

end

假设您有一个文件text_file.txt,其中包含您上面给出的内容,然后运行:

readLineBasedOnHeader('Header A (2x3):', 'text_file.txt') 应该返回:

ans =

     3     6     7
     5     8     8

并运行:

readLineBasedOnHeader('Header B (4x4):', 'text_file.txt')

应该返回:

ans =

    23    65     2     6
     4     6     7     8
    33     7     8     9

请注意,这需要您输入完整的标题行(即与行完全匹配);但我相信你可以玩弄它来匹配Header A 位。

【讨论】:

    【解决方案2】:

    另外,尝试使用这段代码:

    infilename = '1.txt'; % name of your file
    m = memmapfile(infilename);  % load file to memory (and after close it)
    instrings  = strsplit(char(m.Data.'),'\n','CollapseDelimiters',true).';
    
    checkstr = 'Header B';
    % find all string (their indices) starting with checkstr 
    ind = find(strncmpi(instrings,checkstr,length(checkstr)));
    
    
    data = [];
    if isempty(ind)
       fprintf('\n No strings with %s',checkstr)
    else
       % first string with string checkstr
    
        n = ind(1)+1;
        N = length(instrings);
        while n<=N % find all numerical data after string with `checkstr`
            convert = str2num(instrings{n});
            if isempty(convert), break, end % find non-numerical data
    
            data(end+1,1:length(convert)) = convert; % it because you can have various number of columns
            n = n+1;
        end
    end
    
    data % display load data
    

    输出

    23    65     2     6     7
     4     6     7     8     0
    33     7     8     9     0
    

    对于文件1.txt

    Header A (2x3):
    3 6 7
    5 8 8
    Header B (4x4):
    23 65 2 6 7
    4 6 7 8
    33 7 8 9
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2013-12-26
      • 2011-11-12
      • 2014-10-18
      • 2018-07-31
      相关资源
      最近更新 更多