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 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