如何从文本文件中读取一行以便在matlab中输入

时间:2015-06-24 20:01:11

标签: matlab text-files octave

我正在生成一些3D点并保存在文本文件中。接下来我想把这些点作为另一个代码的输入。这是我的文本文件:

*******OUTPUT 1 for p=0.01 5x5x5********
1 1 4 ;3 2 4 ; 
*******OUTPUT 2 for p=0.01 5x5x5********
2 1 3 ;1 4 4 ; 
*******OUTPUT 3 for p=0.01 5x5x5********
2 1 3 ;1 4 4 ; 

对于输出1 p = 0.01(1,1,4)和(3,2,4)是我的观点。我想匹配输出数和p值,然后抓住那些点(对于那个输出数和p值)作为我的另一个代码的输入。我想做类似下面的事情:

if(*******OUTPUT %d for p=%0.2f 5x5x5*******)

    points = will take the points after that line

end

但不知道该怎么做。任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

此代码会将输出值, p 值和提取到三个单独的数组中。

output=[];
p=[];
points=[];

% open file
fid = fopen('test.txt');

% read the file line by line
tline = fgetl(fid);

% if the line is not empty
while ischar(tline)

    % if it is the 'output' line
    if strcmp(tline(1:13),'*******OUTPUT')

        % extract the output number from the string
        output = [output, sscanf(tline,'%*s %i %*s%*f %*s')];

        % extract p value
        p = [p, sscanf(tline,'%*s %*i%*8c%f %*s')];

    % if it is the 'points' line
    else

        % extract points, sscanf output is transposed
        points = [points; sscanf(tline,'%i %i %i%*2c%i %i %i %*s')'];

    end

    tline = fgetl(fid);
end

% close file
fclose(fid);

提取完值后,您可以随心所欲地做任何事情。