在MATLAB中解析文本文件

在MATLAB中解析文本文件,matlab,parsing,matlab-guide,Matlab,Parsing,Matlab Guide,如何在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下) 有什么帮助吗?您可以使用fgets逐行读取文件,并检查是否包含p和n的行 fid = fopen('pn.txt'); % open the file i2 = 1; data =

如何在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下)


有什么帮助吗?

您可以使用
fgets
逐行读取文件,并检查是否包含
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])

下面是另一个解决方案:

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

谢谢,但最后两行给了我这个错误:使用cell2mat时出错(第46行)输入单元格数组的所有内容都必须是相同的数据类型。您是否使用上面包含的示例文件得到了该错误?我知道您得到了一个可行的答案,但我也更新了我的答案。您的答案现在可以了,非常感谢!谢谢,但是我如何读取数据呢?
out{1}
是第一个数组,
out{2}
-第二个数组,等等。这不是重复的!