使用MATLAB从文本文件中提取数据

时间:2013-09-22 21:04:19

标签: matlab parsing text-files

我有一个以下格式的文本文件:

729 6
===========================================================================
solution 1 :
t :  1.00000000000000E+00   0.00000000000000E+00
m : 1
the solution for t :
 x2 : -1.55155599552781E+00  -2.39714921318749E-46
 x4 : -2.01518902001522E+00   1.29714616910194E-46
 x1 :  1.33015840530650E+00   2.03921256321194E-46
 x6 : -2.10342596985387E+00   1.19910915953576E-46
 x3 :  1.27944237849516E+00   1.99067515607667E-46
 x5 :  2.44955616711054E+00  -1.48359823527798E-46
== err :  2.178E-13 = rco :  2.565E-05 = res :  1.819E-11 ==
solution 2 :
t :  1.00000000000000E+00   0.00000000000000E+00
m : 1
the solution for t :
 x2 :  1.55762648294693E+00   1.44303635803762E-45
 x4 :  2.10025771786320E+00  -6.97912321099274E-46
 x1 : -1.28451613237821E+00  -1.19859598871142E-45
 x6 :  2.01187184051108E+00  -7.54361111776421E-46
 x3 : -1.33529118239379E+00  -1.22818883958157E-45
 x5 : -2.44570040628148E+00   8.62982269594568E-46
== err :  2.357E-13 = rco :  2.477E-05 = res :  1.637E-11 ==

我想使用MATLAB从x1提取变量x6,其中值位于冒号后的第一列。 (例如,x2等于-1.55155599552781E + 00作为第一个解决方案。)

我试过了:

data = textscan(fileID,'%s %s %f %f %f')

但它不起作用。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

我经常喜欢通过乱砍一堆fscanf语句来手动阅读。我做了以下操作来创建文件中每个'解决方案'的结构数组。由于x标签似乎无序,因此您必须小心对它们进行排序或以后正确使用它们:

fid = fopen('data.txt');

% assume the first line is the solution count at the number of x values in
% each solution"
header = fscanf(fid, '%d %d');
numSolutions = header(1); % we could use feof instead
numVals = header(2); % usually 6

% get rid of that '=====' line
fgetl(fid);

% init the solutions:
result(1:numSolutions) = struct('sol', nan, 't', nan, 'm', nan, 'xnum', [], 'xval', []);

for ind=1:numSolutions

    % If the file lied and we find ourselves at the end then just leave.
    if feof(fid)
        result = result(1:ind-1);
        break;
    end

    disp(['Reading ' num2str(ind)]);

    result(ind).sol = fscanf(fid, 'solution %d :\n',1);% read in the solution number
    result(ind).t = fscanf(fid,'t : %f %f\n');
    result(ind).m = fscanf(fid,'m : %f\n');
    fgetl(fid); % read the label line for sol

    % loop through and read each value:
    for ind_val = 1:numVals
        result(ind).xnum(ind_val) = fscanf(fid, ' x%d%*3c');
        result(ind).xval(ind_val) = fscanf(fid, '%f',1);
        val2 = fscanf(fid, '%f\n',1); % we just ignore this
    end

    trashLine = fgetl(fid); % read and ignore the error message

end

fclose(fid);