Getting error while loading .mat file from many directory

1 回表示 (過去 30 日間)
sam moor
sam moor 2017 年 4 月 24 日
編集済み: sam moor 2017 年 4 月 24 日
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".
sam moor
sam moor 2017 年 4 月 24 日
got it thank you very much

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by