MATLAB - 逐行读取文本文件(具有不同格式的行)

问题描述 投票:0回答:1

我有一个这种类型的文本文件(让我们称之为输入文件):

%我的输入文件%注释1%评论2

4%参数F.

2.745 5.222 4.888 1.234%参数X.

273.15 373.15 1%温度初始/最终/步骤

3.5%参数Y.

%矩阵A.

1.1 1.3 1 1.05

2.0 1.5 3.1 2.1

1.3 1.2 1.5 1.6

1.3 2.2 1.7 1.4

我需要读取此文件并将值保存为变量,甚至更好地将其保存为不同数组的一部分。例如,通过阅读我应该获得Array1.F=4;然后Array1.X应该是3个实数的向量,Array2.Y=3.5然后Array2.A是矩阵FxF。有很多函数可以从文本文件中读取,但我不知道如何阅读这些不同的格式。我在过去使用fgetl/fgets来读取行但是它读作字符串,我使用了fscanf,但它读取整个文本文件,好像它的格式全部相同。但是我需要用预定义的格式顺序阅读。我可以通过逐行读取fortran来轻松完成此操作,因为read具有格式声明。 MATLAB中的等价物是什么?

matlab text-files scanf textscan
1个回答
0
投票

这实际上解析了您在示例中发布的文件。我本可以做得更好,但今天我很累:

res = struct();

fid = fopen('test.txt','r');
read_mat = false;

while (~feof(fid))
    % Read text line by line...
    line = strtrim(fgets(fid));

    if (isempty(line))
        continue;
    end

    if (read_mat) % If I'm reading the final matrix...
        % I use a regex to capture the values...
        mat_line = regexp(line,'(-?(?:\d*\.)?\d+)+','tokens');

        % If the regex succeeds I insert the values in the matrix...
        if (~isempty(mat_line))
            res.A = [res.A; str2double([mat_line{:}])];
            continue; 
        end
    else % If I'm not reading the final matrix...
        % I use a regex to check if the line matches F and Y parameters...
        param_single = regexp(line,'^(-?(?:\d*\.)?\d+) %Parameter (F|Y)$','tokens');

        % If the regex succeeds I assign the values...
        if (~isempty(param_single))
            param_single = param_single{1};
            res.(param_single{2}) = str2double(param_single{1});
            continue; 
        end

        % I use a regex to check if the line matches X parameters...
        param_x = regexp(line,'^((?:-?(?:\d*\.)?\d+ ){4})%Parameter X$','tokens');

        % If the regex succeeds I assign the values...
        if (~isempty(param_x))
            param_x = param_x{1};
            res.X = str2double(strsplit(strtrim(param_x{1}),' '));
            continue; 
        end

        % If the line indicates that the matrix starts I set my loop so that it reads the final matrix...
        if (strcmp(line,'%Matrix A'))
            res.A = [];
            read_mat = true;
            continue;
        end
    end
end

fclose(fid);
© www.soinside.com 2019 - 2024. All rights reserved.