how to make a loop for reading and merging .mat files

965 Views Asked by At

I am trying to read in .mat files from the specified folder. I want to load them two at a time in consecutive order, merge them together, save the number of columns i want as a new .mat file, and keep doing this for all the files (i will eventually have alot).

Each .mat file has the same number of variables and column length. They represent one day of data, so 24 columns is 24 hours, and i want this to contain 25 hours.

Here is an example I have done of what i want to achieve, but unsure how to have this looping through all the files in the folder properly and saving the new files:

folder_dir = ('myfolder');
mat_files = dir(fullfile(folder_dir, '*.mat')); 

for i = 1:(length(mat_files)) 

A = load(mat_files(i));
B = load(mat_files(i+1)); 
AB = [A,B];

var1 = [AB.var1]; % concatenate so each file is now 2 days of data (48 hours) 
var2 = [AB.var2];

var1 = var1(:,(1:25)); % extract the first 25 columns (25 hours)
var2 = var2(:,(1:25));

% save them all as final .mat files with 25 time levels
save 2019_sample1.mat var1 var2 

end 

so i want to be able to loop through all my .mat files, merge the previous file with the next file and extract the 1st 25 time levels and save as a new .mat file.

Any help on how i can make the loop would be great. Thank you

1

There are 1 best solutions below

0
On BEST ANSWER

I assume you are having trouble loading and saving files programmatically. You can access the list of files in MATLAB with the function dir(). For programmatically loading / saving, I recommend using the function syntax save() and load() instead of the command syntax save and load

Here is an example script I'd use. This assumes the input directory you use will only have .mat files. Read this thread for a detailed step-by-step of how this script works.

input_path = './your_data_dir/' % Set the directory you will be loading your data from
output_path = './your_output_dir/' % Set the directory you want to save the output to
list = dir(input_path); % Get list of files
file_list = {list.name}; % Store filenames in a cell array
file_list(1:2) = []; % Delete the inodes '.' and '..' from files list

% Loop through each file in the directory, from file 1 to file N-1
for i = 1:(length(file_list)-1)
    % Get file names, use curly brackets to extract string from cell array
    file_A = file_list{i}; 
    file_B = file_list{i+1};

    % Load the data
    var_A = load(file_A);
    var_B = load(file_B);

    % Format data
    var_combine = [var_A, var_B];

    % Your Code
    var1 = [var_combine.var1]; 
    var2 = [var_combine.var2];
    var1 = var1(:,(1:25));
    var2 = var2(:,(1:25));

    % Use sprintf() to automatically generate filenames
    save_name = sprintf("%scombined_data_%d", output_path, i);

    % Save data
    % Note the quote marks for `var1` and `var2`, they are required
    save(save_name, 'var1', 'var2')
end