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

MATLAB - Read Textfile (lines with different formats) line by line

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

%My kind of input file % Comment 1 % Comment 2

4 %Parameter F

2.745 5.222 4.888 1.234 %Parameter X

273.15 373.15 1 %Temperature Initial/Final/Step

3.5 %Parameter Y

%Matrix 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 中的等价物是什么?

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

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);