以下方法可行,但如果您要处理大量数据,则可能不会那么快:
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 位。