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
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 syntaxsave()
andload()
instead of the command syntaxsave
andload
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.