3

如何在 MATLAB 中解析文件?文本中的数据格式如下:

p
15.01245  20.478
12.589  58.256
n
16.589  87.268
52.367  46.256
2.589  58.02

我想将每个数据存储在单独的数组中(;将数据存储在数组 1 中的字母 p 下,并将数据存储在数组 2 中的字母 n 下)。

有什么帮助吗?

4

2 回答 2

4

您可以通过使用fgetsto 逐行读取文件并检查包含p和的行来做到这一点n

fid = fopen('pn.txt'); % open the file
i2 = 1;
data = {};
while ~feof(fid) % loop over the following until the end of the file is reached.
      line = fgets(fid); % read in one line
      if strfind(line,'p') % if that line contains 'p', set the first index to 1
          i1 = 1;
      elseif strfind(line,'n') % if that line contains 'n' set the first index to 2
          i1 = 2;
      else
          data{i1,i2} =  str2num(line); % otherwise, it the line contains numbers, add them to a cell array.
          i2 = i2 + 1;
      end
end
fclose(fid);

%convert the cell array into two matrices.
p = cell2mat(data(1,:));
p = reshape(p,[numel(p)/2,2])
n = cell2mat(data(2,:));
n = reshape(n,[numel(n)/2,2])
于 2013-04-01T19:59:00.170 回答
4

这是另一个解决方案:

fstring = fileread('test.txt'); % read the file as one string
fblocks = regexp(fstring,'[A-Za-z]','split'); % uses any single character as a separator
fblocks(1) = []; % removes anything before the first character
out = cell(size(fblocks));
for k = 1:numel(fblocks)
    out{k} = textscan(fblocks{k},'%f %f','delimiter',' ','MultipleDelimsAsOne', 1);
    out{k} = horzcat(out{k}{:});
end
于 2013-04-01T20:19:27.257 回答