MATLAB: Array is stopping at lower variable count

arrayfolderfor loopMATLAB

Hello,
I am loading variaous variable from different files from different folders in the same directory into an array. For the moment I have 2 folders to load. Folder 1 contains 4 files (variables) and Folder 2 contains 21 files (variables). The code runs perfectly for number of files but now the array is not loading all the files from the second folder. it is stopping at just the lower limit of file count, i.e. for this example at 4. I want it to read and load all files from both folders and put 0 if the data is not available. Pleas find below the code and help me!
Thank you
clc
clear all
close all
c=Constants;
Folders= dir;
Folders = Folders([Folders.isdir] & ~strncmpi('.', {Folders.name}, 1));
for w=numel(Folders)
currd=Folders(w).name;
cd (currd)
F = dir('*.txt');
nF = length(F) ;
count = 0 ;
A=100;
for j=1:nF
fname = F(j).name ;
filename = fullfile(fname);
pieces = regexp(filename, '\_', 'split');
sitename= pieces{1};
I=str2num(sitename);
fileID = fopen(filename);
formatSpec = '%s';
N = 1;
c_text= textscan(fileID,formatSpec,N,'Delimiter',' ');
c_data= textscan(fileID,'%f %f');
if I>60
i{j,w}=I;
else
i{j,w}=-c_data{1}/1000;
end
v{j,w}=c_data{2};
end
fclose(fileID)
end
cd ..

Best Answer

  • for w=numel(Folders)
    This "loops" over one value, which means you're only going to access the files in the last element of Folders.
    Since you indicated you're using release R2018b, I recommend using dir with a wildcard to search through the folders recursively. See the "Find Files in Subfolders" example on the documentation page for dir for an example of the syntax. The example only displays the files, but you can call dir with an output and use the fullfile function to assemble the full path from the folder and name fields of elements of the struct array it returns.