如果txt文件中有空白单元格,matlab importdata会产生奇怪的输出

z0qdvdin  于 7个月前  发布在  Matlab
关注(0)|答案(1)|浏览(68)

我想在matlab中导入以下txt文件。

Run       Local       Local      Local    Local   First-order
   Index     exitflag      f(x)     # iter   F-count   optimality
       1       -10                               14
       2         3    1.239e-09        39        40     3.484e-06
       3         3    3.028e-22        45        46     2.174e-12
       4       -10                                4
       5       -10                                7
       6         3    5.749e-13        17        18     5.438e-08
       7       -10                                3
       8       -10                                2
       9       -10                                5
      10       -10                                1
      11       -10                                2
      12       -10                                3
      13       -10                                5
      14       -10                                1
      15       -10                                2
      16       -10                                2

MultiStart completed some of the runs from the start points.

3 out of 16 local solver runs converged with a positive local solver exit flag.

字符串
正如你所看到的,有几个空白单元格和文本行在文件的结尾和开头。我只对数字数据感兴趣,这是一个16x6矩阵的特定txt文件。空单元格是NaN。
Importdata能够将文本与数值数据分开,但是,它认为只有3列,因为第一行有三个空白单元格。如果我手动删除文本行并调用readtable(),则无论出于何种原因,缺少数值数据的前三行。
如何从文本文件中获取16x6矩阵,其中空白单元格= NaN?

bogh5gae

bogh5gae1#

我会考虑使用正则表达式来代替一些函数,比如readtable()。但是下面的代码不是通用的,只是建议。

fid = fopen('result.txt');
data = '';
while ~feof(fid)
  tline = fgets(fid);
  data = [data, tline];
end
fclose(fid);

pattern1 = '\d.+?\r';
match = regexp(data,pattern1,'match');
match = match(:);

result = cell(numel(match), 6);
for k = 1 : numel(match)
  target = match{k};
  pat1 = '(\d{1,2})\s+(\S+?)\s+(\S+?)\s+(\S+?)\s+(\S+?)\s+(\S+)';
  tokens = regexp(target,pat1,'tokens');
  if ~isempty(tokens)
    result(k,:) = vertcat(tokens{:});
  else
    pat1 = '(\d{1,2})\s+(\S+?)\s+(\S+)';
    tokens = regexp(target,pat1,'tokens');
    result(k,[1,2,5]) = vertcat(tokens{:});
  end
end

result(cellfun(@isempty, result)) = {''};
result = str2double(result);

disp(result)

字符串

相关问题