如何从matlab中的txt文件中提取数据?

时间:2016-05-26 12:20:59

标签: matlab file access

例如 .txt文件pqfile.txt

255 20
40
1.0 1.3 1.7 1
7.1 7.2 7.3 0
1.1 1.2 1.4 1
6.1 8.2 9.1 0
40
1.0 1.3 1.7 1
7.1 7.2 7.3 0
1.1 1.2 1.4 1
6.1 8.2 9.1 0
40

我只需要

1.0 1.3 1.7 
1.1 1.2 1.4 
1.0 1.3 1.7 
1.1 1.2 1.4
1.0 1.3 1.7 
1.1 1.2 1.4

并希望将其存储为struct 结构{1} 1.0 1.3 1.7 1.1 1.2 1.4

结构{2} 1.0 1.3 1.7 1.1 1.2 1.4

结构{3} 1.0 1.3 1.7 1.1 1.2 1.4

1 个答案:

答案 0 :(得分:0)

您可以使用textscan忽略前两行(通过指定HeaderLines),然后抓取其他所有内容,然后可以索引结果并仅检索每一行。

fid = fopen('pqfile.txt', 'r');

% Ignore the first two lines and read the rest of the data in as floats
alldata = textscan(fid, '%f', 'HeaderLines', 2);
alldata = reshape(alldata{1}, 4, []).';

% Only keep every other row and only the first 3 columns
data = alldata(1:2:end, 1:3);

%   1   1.3  1.7
% 1.1   1.2  1.4

<强>更新

发布实际数据后,这是一个应该在块上正常运行的版本。

fid = fopen('pqfile.txt', 'r');
% Read and ignore the first line
fgetl(fid);

result = {};

% Loop until we hit the end of the file
while ~feof(fid)
    % Figure out how many lines to read
    nLines = fscanf(fid, '%d', 1);

    % Now read this many lines
    data = textscan(fid, '%f', nLines * 4); 

    % Now reshape this data
    data = reshape(data{1}, 4, []).';

    % Add the data to the overall data structure
    if ~isempty(data)
        result = cat(1, result, {data(1:2:end,1:3)});
    end
end