Getting error while loading .mat file from many directory

1 次查看(过去 30 天)
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.

回答(1 个)

Stephen23
Stephen23 2017-4-24
编辑:Stephen23 2017-4-24
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 个评论
Stephen23
Stephen23 2017-4-24
编辑:Stephen23 2017-4-24
@sam moor: put the "file" loop inside the "folder" loop. Use the internet and search for "nested loops".

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by