matlabloopsmat-file

How to load and run multiple .mat files in matlab


I am trying to run multiple .mat files in matlab. So far i have 3 .mat files each containing the same variables. I want to run one .mat file and then switch to the next file. They are named like this:

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

The code i have tried to run works for the first .mat file and it then doesnt switch to the second. Ideally i am trying to run all 3 files continuously, as in the future i could have 100s.

This is the code i tried so far:

        % 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 

Any help on how i could get this to run continuously through each mat file would be great. Thank you.


Solution

  • A very easy method , just select all the files (Ctrl + A) - drag and drop them into the command window (be sure to drag the first file to load them in same order).

    Or You can use this

    % 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
    

    Or

    % 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