如何只将数值数据读入Matlab并忽略任何文本

时间:2014-01-16 11:15:41

标签: matlab textscan

我正在尝试将数据读入由数字和文本行组成的Matlab中,但我只想读取数值并跳过文本(无论何时发生)。我一直在使用文本扫描但是要读取数字,但当它到达带有文本的列时,函数终止。

这是我的第一篇文章,所以我不熟悉如何在这里发布我的数据和代码,所以我附上了一些数据:

0.37364   1.318    0.1090E-02    0.4885E-03    0.236E-02    0.527E-02
0.39237   1.372    0.1214E-02    0.5470E-03    0.211E-02    0.546E-02
0.41129   1.580    0.1612E-02    0.6992E-03    0.142E-02    0.588E-02
 CF SET TO 0.000002 AT X=      0.430 ON SURFACE  1 (1=U/S, 2=L/S)
0.43038   3.070    0.4482E-02    0.1160E-02    0.200E-05    0.905E-02
 HBAR MAX LIMIT REACHED

所以我希望Matlab用数字数据读取列,并跳过包含文本的列。

感谢您的帮助,并提前感谢您!

哈姆扎

2 个答案:

答案 0 :(得分:2)

<强>解决方案

result = [];

fid=fopen('data.txt');
while 1
    tline = fgetl(fid);
    if ~ischar(tline), break, end
    celldata = textscan(tline,'%f %f %f %f %f %f');
    matdata = cell2mat(celldata);
    % match fails for text lines, textscan returns empty cells
    result = [result ; matdata];
end

fclose(fid);

<强>结果

result =
0.3736    1.3180    0.0011    0.0005    0.0024    0.0053
0.3924    1.3720    0.0012    0.0005    0.0021    0.0055
0.4113    1.5800    0.0016    0.0007    0.0014    0.0059
0.4304    3.0700    0.0045    0.0012    0.0000    0.0091

<强> data.txt中

0.37364   1.318    0.1090E-02    0.4885E-03    0.236E-02    0.527E-02
0.39237   1.372    0.1214E-02    0.5470E-03    0.211E-02    0.546E-02
0.41129   1.580    0.1612E-02    0.6992E-03    0.142E-02    0.588E-02
 CF SET TO 0.000002 AT X=      0.430 ON SURFACE  1 (1=U/S, 2=L/S)
0.43038   3.070    0.4482E-02    0.1160E-02    0.200E-05    0.905E-02
 HBAR MAX LIMIT REACHED

答案 1 :(得分:0)

我提出了以下解决方法:

    m=1;
    for k=1:10;    % create for loop ranging from start to finish of data
        ful = sscanf(S{k,1},'%f');  % scan each line for a floating point number
        le=size(ful);               % gives size of the scanned values

        if le(1) > 0                % Only read if there is a value of > 0 ( for non-floating i.e. string, the value = 0)
            for t=1:le(1)
                data1(m,t)=ful(t);  % store the value in matrix
            end
            m=m+1;
        end
    end

这似乎可以解决问题!

相关问题