MATLAB: Opening the only file in a directory with certain extension

openfiles

I have used MATLAB in conjunction with another piece of software to generate a huge amount of data, each placed neatly in a directory that corresponds to certain variable parameters of the data. Each individual directory contains 5 files, and the one I am interested has the extension '.spe'. I am using MATLAB to navigate to every folder and read the data in the '.spe' file, however each '.spe' file has a different name according to the variables used. The code I'd like to use looks something like this:
for i=1:freq1max
Freq1=i*increment1;
foldername1=[num2str(Freq1),'_Hz']; %first variable directory
for j=1:freq2max
Freq2=j*increment2;
foldername2=[num2str(Freq2),'_Hz']; %second variable directory
cd(fullfile(/.../),foldername1,foldername2); %navigate to directory
spectrum=textread('*.spe'); %this is where the program fails
...... %data analysis and output here
end
end
however this does not work. I have tried to implement ideas I have found on this website and others with no success. Any ideas? Thank you all in advance for the help. Cheers.

Best Answer

To get only a list of the .spe files, use the dir function to get a list of them, then go through the list:
cd(fullfile(/.../),foldername1,foldername2); %navigate to directory
spe_files = dir('*.spe');
for k1 = 1:length(spe_files)
spe_names{k1} = spe_files(k1).name;
end
The ‘spe_names’ cell array will have all the file names.
You can then go through the list and load each one.