首页 > 解决方案 > 如何在 matlab 中加载和运行多个 .mat 文件

问题描述

我正在尝试在 matlab 中运行多个 .mat 文件。到目前为止,我有 3 个 .mat 文件,每个文件都包含相同的变量。我想运行一个 .mat 文件,然后切换到下一个文件。它们是这样命名的:

        file2019_1.mat %day 1
        file2019_2.mat %day 2
        file2019_3.mat %day 3

我尝试运行的代码适用于第一个 .mat 文件,然后它不会切换到第二个。理想情况下,我试图连续运行所有 3 个文件,因为将来我可能有 100 个。

这是我到目前为止尝试的代码:

        % set up folder for .mat files containing variables of interest 
        myFolder = ('filepath');
        filePattern = fullfile(myFolder, 'file2019_*.mat');
        fileList = dir(filePattern);

        % set up variable data (here it is daily mean velocity value) 
        % hourly, m/s (one mat file one day)
        number_mat = length(fileList);
        for i = 1:number_mat
        load(['file2019_' num2str(i) '.mat'])

        %%%% run model in here

        end 

关于如何让这个在每个 mat 文件中连续运行的任何帮助都会很棒。谢谢你。

标签: matlabloopsmat-file

解决方案


一个非常简单的方法,只需选择所有文件(Ctrl + A) - 将它们拖放到命令窗口中(确保拖动第一个文件以相同顺序加载它们)。

或者你可以使用这个

% Read files mat1.mat through mat20.mat
for k = 1 : 20  % or whatever your numbers of files
    % Create a mat filename, and load it into a structure called matData.
    matFileName = sprintf('mat%d.mat', k);
    if isfile(matFileName)
        matData = load(matFileName);
    else
        fprintf('File %s does not exist.\n', matFileName);
    end
    
end

或者

% Get a list of all txt files in the current folder, or subfolders of it.

fds = fileDatastore('*.txt', 'ReadFcn', @importdata)

fullFileNames = fds.Files

numFiles = length(fullFileNames)

% Loop over all files reading them in and plotting them.

for k = 1 : numFiles

    fprintf('Now reading file %s\n', fullFileNames{k});

    % Now have code to read in the data using whatever function you want.

    % Now put code to plot the data or process it however you want...

end

推荐阅读