MATLAB: Loop over subfolders and saving cat parameters

concatenateloop over subfolders

Hello All,
I am trying to run my code over sub folder but facing issues. I am trying to extrac perticular variable from multiple .mat files.
I could do that for 1 folder having multiple .mat files with following code:
clear all
close all
d = uigetdir();
filePattern = fullfile(d, '*.mat');
file = dir(filePattern);
x = cell(1, numel(file));
for k = 1: numel(file)
baseFileName = file(k).name;
fullFileName = fullfile(d, baseFileName);
fprintf('Now Reading file %s\n', fullFileName);
x{k}=load(fullFileName,'Veriable1');
j{k}=cell2mat(struct2cell(x{k}));
end
var1=cat(1,j{:});
Now I am trying to run this over the loop for subfolder and now facing issues and need help
Here is my current try:
clear all
close all
D = 'myPath';
S = dir(fullfile(D,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list of subfolders of D.
for ii = 1:numel(N)
T = dir(fullfile(D,N{ii},'*.mat')); % improve by specifying the file extension.
C = {T(~[T.isdir]).name}; % files in subfolder.
for jj = 1:numel(C)
filePattern = fullfile(D,N{ii},C{jj})
%filePattern = fullfile(F, '*.mat');
file = dir(filePattern);
x = cell(1, numel(file));
for k = 1: numel(file)
baseFileName = file(k).name;
fullFileName = fullfile(D,N{ii}, baseFileName);
fprintf('Now Reading file %s\n', fullFileName);
x{k}=load(fullFileName,'Veriable1');
j{k}=cell2mat(struct2cell(x{k}));
end
end
end
var1=cat(1,j{:});
I know it has many flaws but I am not at all able to think further and need help to make it work.

Best Answer

If you only need to loop over subfolders then why are you using three loops? One loop for the subfolders, one loop for the files... it is not clear what the third loop is supposed to achieve.
Also you do not explain if each folder only contains one .mat file or multiple .mat files, which will make a large difference to the design of your code.
Something like this will get you started:
D = 'C:\Software\Data\EDP\Rotation_3_CES_OBD\Script_for_data_analysis\19-11_matfiles\Try_subf';
S = dir(fullfile(D,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list of subfolders of D.
for ii = 1:numel(N)
T = dir(fullfile(D,N{ii},'*.mat')); % improve by specifying the file extension.
T([T.isdir]) = [];
for jj = 1:numel(T)
F = fullfile(D,N{ii},T(jj).name)
fprintf('Now Reading file %s\n',F);
Z = load(F,'Key_swtich');
T(jj).data = Z.Key_switch;
end
S(ii).data = vertcat(T.data);
end
X = vertcat(S.data)