Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab中从数据文件文本中提取数值数据_Matlab_Text_Import_Cell_Cell Array - Fatal编程技术网

Matlab中从数据文件文本中提取数值数据

Matlab中从数据文件文本中提取数值数据,matlab,text,import,cell,cell-array,Matlab,Text,Import,Cell,Cell Array,我有一个.txt数据文件,它的开头有几行文本注释,后面是实际数据的列。它看起来像这样: lens (mm): 150 Power (uW): 24.4 Inner circle: 56x56 Outer Square: 256x320 remarks: this run looks good 2.450000E+1 6.802972E+7 1.086084E+6 1.055582E-5 1.012060E+0 1.036552E+0 2.400000E+1 6.86659

我有一个.txt数据文件,它的开头有几行文本注释,后面是实际数据的列。它看起来像这样:

lens (mm): 150
Power (uW): 24.4
Inner circle: 56x56
Outer Square: 256x320
remarks: this run looks good            
2.450000E+1 6.802972E+7 1.086084E+6 1.055582E-5 1.012060E+0 1.036552E+0
2.400000E+1 6.866599E+7 1.088730E+6 1.055617E-5 1.021491E+0 1.039043E+0
2.350000E+1 6.858724E+7 1.086425E+6 1.055993E-5 1.019957E+0 1.036474E+0
2.300000E+1 6.848760E+7 1.084434E+6 1.056495E-5 1.017992E+0 1.034084E+0
通过使用
importdata
,Matlab自动分离文本数据和实际数据。但是如何从文本(以单元格格式存储)中提取这些数字数据呢?我想要实现的目标是:

  • 提取这些数字(例如150、24.4)
  • 如果可能,提取名称(“镜头”、“电源”)
  • 如果可能,提取单位(“mm”、“uW”)

  • 1是最重要的,2或3是可选的。如果可以简化代码,我也很乐意更改文本注释的格式。

    假设您的示例数据保存为
    demo.txt
    ,您可以执行以下操作:

    function q47203382
    %% Reading from file:
    COMMENT_ROWS = 5;
    % Read info rows:
    fid = fopen('demo.txt','r'); % open for reading
    txt = textscan(fid,'%s',COMMENT_ROWS,'delimiter', '\n'); txt = txt{1};
    fclose(fid);
    % Read data rows:
    numData = dlmread('demo.txt',' ',COMMENT_ROWS,0);
    %% Processing:
    desc = cell(5,1);
    unit = cell(2,1);
    quant = cell(5,1);
    for ind1 = 1:numel(txt)
      if ind1 <= 2
        [desc{ind1}, unit{ind1}, quant{ind1}] = readWithUnit(txt{ind1});
      else
        [desc{ind1},             quant{ind1}] = readWOUnit(txt{ind1});
      end
    end
    %% Display:
    disp(desc);
    disp(unit);
    disp(quant);
    disp(mat2str(numData));
    end
    
    function [desc, unit, quant] = readWithUnit(str)
      tmp = strsplit(str,{' ','(',')',':'});
      [desc, unit, quant] = tmp{:};
    end
    
    function [desc, quant] = readWOUnit(str)
      tmp = strtrim(strsplit(str,': '));   
      [desc, quant] = tmp{:};
    end
    
    (为了便于查看,我随意对输出进行了一些格式化。)

    另请参见:.

    可能的副本