Load multiple *.mat files and save outputs using loop without overwriting the previous file
Show older comments
I'm new to Matlab. The goal of my code is to load *.mat files from a given folder and perform the following:
- Load the data from each file
- Output the file name excluding the path for each file to be later used in a plot legend
I can do this for each file individually but using my for loop, the previous file is overwitten and I end up with only one output (the last file in the folder).
For the file name output, I have attempted to create a cell array named "Out" but I get the following error: Unable to perform assignment because the left and right sides have a different number of elements. I know that the size of my cell aray need to match the size of the output but I'm not sure how to create a cell array of the right size when the outputs are different for each file.
This still doesn't address the data itself being overwritten during each iteration of the loop.
% Specify the folder where the files live.
myFolder = 'enter folder directory here';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
filePattern = fullfile(myFolder, '*.mat');
theFiles = dir(filePattern);
% n=theFiles.name(1).Value
x=size(theFiles);
Out = zeros(length(theFiles),1);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name
fullFileName = fullfile(theFiles(k).folder, baseFileName)
[~,name,~] = fileparts(fullFileName)
load(fullFileName)
Out(k)=basefilename
end
Thanks in advance. Sorry if I left anything important out.
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!