在MATLAB中解析文本文件

3
我该如何在MATLAB中解析文件?文本中的数据格式如下:
p
15.01245  20.478
12.589  58.256
n
16.589  87.268
52.367  46.256
2.589  58.02

我希望把每个数据存储在单独的数组中(例如:将字母“p”下的数据存储在数组1中,将字母“n”下的数据存储在数组2中)。

需要帮助吗?


这不是一个重复的内容! - 0x90
2个回答

4
你可以使用 fgets 按行读取文件,并检查包含 pn 的行。
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])

谢谢,但最后两行给了我这个错误: Error using cell2mat (line 46) 输入单元数组的所有内容必须是相同的数据类型。 - userInThisWorld
您是否在使用上面提供的示例文件时遇到了该错误? - Molly
我看到你已经有了一个可行的答案,但是我也更新了我的答案。 - Molly

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

谢谢,但我如何读取数据? - userInThisWorld
out{1} 是第一个数组, out{2} 是第二个,以此类推。 - yuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接