Getting error while loading .mat file from many directory
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I have main directory named'data' and sub directories (r1,r2,r3...). In each sub directory, I have several folders(r1_0.05,r1_0.10,...) and .mat file as shown in figure below. I am using below code to load .mat file from each sub-directory and do some operation.
close all; clear all; clc;
project_dir = pwd(); %or give a particular directory name
mainDirContents = dir(project_dir);
mainDirContents(~[mainDirContents.isdir]) = []; %remove non-folders
mask = ismember( {mainDirContents.name}, {'.', '..'} );
mainDirContents(mask) = []; %remove . and .. folders
num_subfolder = length(mainDirContents);
nod=1;
for subfold_idx = 1 : num_subfolder
subfolder_name = mainDirContents(subfold_idx).name;
this_folder = fullfile( project_dir, subfolder_name );
matContents = dir( fullfile(this_folder, '*.mat') );
this_mat = fullfile( this_folder, matContents(subfold_idx).name );
loadmatfile=load(this_mat);
% do operation for each .mat file of the current folder
end
But I am getting error as Index exceeds matrix dimensions.
Error in Untitled5 (line 14) this_mat = fullfile( this_folder, matContents(subfold_idx).name );
Any idea to solve this is highly appreciated. Thank you.
0 Kommentare
Antworten (1)
Stephen23
am 24 Apr. 2017
Bearbeitet: Stephen23
am 24 Apr. 2017
Your indexing is incorrect, and you need another loop.
Basically you are looping over the directories, but then you try to use the directory iteration variable to indexing into the file structure. Here is the relevant part of your code:
for subfold_idx = 1 : num_subfolder
...
matContents = dir( fullfile(this_folder, '*.mat') );
... matContents(subfold_idx).name
end
For example, imagine if there are two directories, then subfold_idx will have values 1 and 2. But if there is only one .mat file in the second directory, then it will be an error to try to use subfold_idx with value 2 ! (because there is no second file).
You need to add another loop of for the files.
3 Kommentare
Siehe auch
Kategorien
Mehr zu File Operations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!