MATLAB: Reading/writing in data from set of text files in loop

file openloopsMATLABmatrixtext filetextscan

I have ten text files, each containing a column of data I wish to read in matlab to arrange in a matrix. The files I am reading are named "test 1.001" "test 1.002" through *.010. Of note is that the test number changes as well (test 1 -> test 2… etc). I have managed to write some code that reads in the text files for one test, but I want to be able to expand this to read in the corresponding files for any test number. I was wondering if there was a way to condense what I have into a loop statement to make this possible?
I have attached a sample test text file and a portion of the code I have to show what I have done. (File paths and some names are changed for representation)
%%%%%%%%
%Portion of code I use
%sample_stopcount and lopoff are values I calculate in another part of code, but should be the same across all data files
Mydata = zeros(100000, 10);
filename = fullfile('C:/Users/me/Documents/MATLAB/test 1.001');
fid = fopen(filename, 'r');
data1 = textscan(fid, '%f', sample_stopcount, 'Headerlines', lopoff);
%start reading data at the 1035th line in file
Mydata = data1{1}; % takes data and puts into #x1 matrix
fid = fclose(fid);
filename2= fullfile('C:/Users/me/Documents/MATLAB/test 1.002')
fid = fopen(filename2,'r')
data2 = textscan(fid, '%f', sample_stopcount, 'Headlines', lopoff);
Mydata2 = data2{1};
fid=fclose(fid);
%

%
%continues on for Mydata10
final = [Mydata Mydata2 Mydata3 etc]
%Want to condense this into a loop and make the fullfile read in for a changing file name and extension

Best Answer

You can use 'sprintf' command in a loop to achieve this. Something like this:
Mydata = zeros(100000, 10);
for i=1:1 % Number of test1->test2 set of files
for j=1:10 % Number of test 1.001->test 1.002 set of files
k=i+(j/1000);
myfilename= sprintf('test %f.txt',k);
filename = fullfile('C:\','Users','me','Documents','MATLAB',myfilename);
fid = fopen(filename, 'r');
Mydata(:,j) = textscan(fid, '%f', sample_stopcount, 'Headerlines', lopoff);
%use the index i to create multiple 'Mydata' when reading test1->test2 etc.
fid = fclose(fid);
end
end