Matlab:如何通过指定标题名称来读取和提取矩阵?

时间:2016-10-06 06:20:07

标签: matlab matrix text-files

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

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中做到吗?

提前致谢!!

2 个答案:

答案 0 :(得分:2)

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

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位匹配。

答案 1 :(得分: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