Getting error while loading .mat file from many directory

1 visualización (últimos 30 días)
sam moor
sam moor el 24 de Abr. de 2017
Editada: sam moor el 24 de Abr. de 2017
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.

Respuestas (1)

Stephen23
Stephen23 el 24 de Abr. de 2017
Editada: Stephen23 el 24 de Abr. de 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 comentarios
Stephen23
Stephen23 el 24 de Abr. de 2017
Editada: Stephen23 el 24 de Abr. de 2017
@sam moor: put the "file" loop inside the "folder" loop. Use the internet and search for "nested loops".
sam moor
sam moor el 24 de Abr. de 2017
got it thank you very much

Iniciar sesión para comentar.

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by