2014-01-16 672 views
0

我想读取数据到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的与读取列数字数据并跳过包含文本的数据。

我很感谢您的帮助,并提前致谢!

哈姆扎

+0

如果将此文件保存为excel文件是可能的,则使用'xlsread'可以很容易地将文本和数字组合在一起。 –

+0

如果你想继续使用'textscan',你的意思是你想跳过包含非数值数据或*列*的*行*?具有非数值数据的行似乎很难划分为列... – darthbith

+0

带有文本的行可以以“CF”或“HBAR”以外的其他行开头吗?有多少种不同类型的文本行? – horchler

回答

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 
+0

谢谢你,托德,我没有机会尝试你的方法,因为我想出了另一种方式,但非常感谢你发布这个答案! – user3202209

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 

这似乎这样的伎俩!

相关问题