Using for loop to load multiple mat files of different names

Hi guys, I'm new to matlab, I'm trying to load multiple mat files from a folder, I had googled for a few ways to solve this question, but none of them solve mine. My .mat file are all different name, such like 2011_003260, 2011_003255 and bla bla bla, as you can see, it is not a continuous number, and not a string, so, how can i loop it with a for loop? Besides of that, I would like to save the information in my .mat file into a table, is there any way I can do it?
files = dir('*.mat'); %try to look for all the .mat files under the folder
for i=1:length(files)
load([files '.mat']); %load the files
SBDInfo(TotalObjIndex).ImageName = ImgName; %Save the information into the 'variables- files'/ 'field'
end

1 Comment

can you please tell me how can i load all the audio files (.wav) into matlab .i tried using different methods and loops but nothing is working

Sign in to comment.

Answers (3)

Hi Jonathan,
You are quite close. If you want to process all the files whose name matches a pattern in a directory, you can use DIR to select the files.
myFolder = 'C:\Documents and Settings\MATLAB\'; % Define your working folder
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
baseFileName = matFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
matData(k) = load(fullFileName);
end
Regards,

9 Comments

Thanks for the answer! Actually I figured out the answer already and it was actually quite simple, lol
files = dir('*.mat'); %try to look for all the .mat files under the folder
totalObjCounter = 1;
for i=1:length(files)
load(files(i).name);%load the files
SBDInfo(totalObjCounter).ImageName = files(i).name;
totalObjCounter = totalObjCounter + 1;
end
In my case if I apply files = dir('*.mat'); it does not gives me all .mat files. Where I may be mistaken?
dir('*.mat') would only look in the current directory. Also, it is possible that the file extensions are not .mat -- there might be a hidden file extension after that. You should use
ls
to see a list of all of the files in the current directory for debugging purposes.
Actually my code goes like this:
I have differnt folders contained in a folder and I need to access mat files inside that folder, so I am using as below:
fpath = dir(fullfile([action_dir,'*.mat']));
But using this while debugging my code in every iteration this is showing file *.mat.
fpath = dir(fullfile( action_dir, '*.mat'));
filenames = fullfile(action_dir, {fpath.name});
Thanks for quick reply but this code is creating structure filename and putting all files in that but I want to access each mat file in my further code.
The variable filenames is a cell array of character vectors, not a structure. You can loop through the contents:
numfiles = length(filenames):
results = cell(numfiles, 1);
for K = 1 : numfiles
thisfile = filenames{K};
datastruct = load(thisfile);
xyz = datastruct.xyz; %extract particular variable
processed_xyz = Process_this_variable(xyz); %call appropriate function to handle the data
results{K} = processed_xyz;
end
Thank you so much for help now I am able to access the file.
It worked perfectly well, but can you explain the code for understanding.

Sign in to comment.

Hello Konstantinos Sofos,
Your code seems to be working as far reading the files, however after reading several files, i get an error indicating
Subscripted assignment between dissimilar structures.
Error in scrap (line 62)
matData(k) = load(fullFileName);s
The code is
myFolder = '/Users/redhwanmawari/Documents/MATLAB/2DimenstionalTestingGT20150907/LOS0dbm15ft_finalData'; % Define your working folder
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
baseFileName = matFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
matData(k) = load(fullFileName);
end
Please advise

3 Comments

matData{k} = load(fullFileName);
The error you were receiving indicates that either the files had different variables names in them or else that the variables were stored in a different order in the file. The repair I made is to write the results into a cell array, as cell arrays can have data of different types.
Hey guys, I'm new to matlab and I used Ray's code edited by Water Roberson - thank you so much guys, it worked. The structure resulted from this code contains 2 fields: "Dataset" (containing the whole path of each object) and "data" containing the actual data enclosed in each object. I'm trying to replace the whole path in "Dataset" with just the name of each object, but I'm struggling.
Example: I would like to replace '/data/RAW/EEG_LAPTOP/Raw Files/eegfile1.eeg' (contained in the first row of the "Dataset" field, with just "eegfile1". And I'm trying to do this for all the files, "eegfile2", "eegfile3" and so on. Any suggestion would be most welcome.
Thanks!
[~, YourStruct(INDEX).Dataset] = fileparts(YourStruct(INDEX).Dataset);
You can vectorize to do the whole struct at the same time:
[~, temp] = fileparts({YourStruct.Dataset});
[YourStruct.Dataset] = deal(temp{:});

Sign in to comment.

Thanks that took care of the error that i had. Now i am trying to convert all the matrices from 18 by 18 matrices in each file into one single column i.e 324 by 1 column. After that once all the files contain one single column, i need to combine all the files into one single column. The code is as follows however i keep getting this error:Argument to dynamic structure reference must evaluate to a valid field name.
Error in scrap (line 70)
rawdata.(reshapedData{p}) = reshape(rawdata.(matData{j}),324,1);
Below is the code i wrote:
p=1;
for j=1:length(matFiles)
rawdata.(reshapedData{p}) = reshape(rawdata.(matData{j}),324,1);
p=p+324;
end
% % Concatenate data
for k = 1:length(matfiles)
rawdata.(matData{k}) = [rawdata.(matData{k});rawdata.(matData{k})];
end

Asked:

on 2 Jun 2015

Commented:

on 21 May 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!