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

时间:2017-12-29 13:40:57

标签: matlab text-files scanf textscan

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

  

%我的输入文件种类%评论1%评论2

     

4%参数F

     

2.745 5.222 4.888 1.234%参数X

     

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

     

3.5%参数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

我需要读取此文件并将值保存为变量,甚至更好地将其保存为不同数组的一部分。例如,通过阅读我应该获得public static void switchWindow(WebDriver driver) throws IOException { parentWindow = driver.getWindowHandle(); new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2)); for (String winHandle : driver.getWindowHandles()) { if (!parentWindow.equalsIgnoreCase(winHandle)) driver.switchTo().window(winHandle); //you can do anything on the new tab/window } } ,然后Array1.F=4;应该是3个实数的向量,Array1.X然后Array2.Y=3.5是矩阵Array2.A。有很多功能可以从文本文件中读取,但我不知道如何阅读这些不同的格式。我在过去使用FxF来读取行但是它读为字符串,我使用了fgetl/fgets但是它读取整个文本文件,好像它的格式全部相同。但是我需要用预定义的格式顺序阅读。我可以通过逐行读取fortran来轻松完成此操作,因为read具有格式声明。 MATLAB中的等价物是什么?

1 个答案:

答案 0 :(得分: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);
相关问题