MATLAB: Opening Sequential .txt Files and Populating Array with Data

cell arraysmultiple files

Hello All,
I would like to write a scrip that will open multiple tab delimited, headerless .txt files from a folder (ex file name "Test1" "Test2" etc) and have the second column copied into an array of zeroes. So far I have tried to follow a similar case I found here:
%This scrip is designed to open multiple .txt files containing %data and write the second column of data into an array.
%1)Set-up File Directory
%Copy folder path here:
MyFolder = Users/Chris/Desktop/Test;
TextFiles = dir(Users/Chris/Desktop/Test .txt);
%Create and array of zeros to rewrite data over
Absorbance = zeroes (2048, 63); %2048 x values and ## spectra files
%3)Import Absorbance Data
for i = 1:63 %Number of spectra files in directory
TextFileNames = ['Test_Absorbance_' num2str(k) '.txt'];
%Open Text File, 'rt' = read text (only works for txt files)
fid = fopen(TextFileNames, 'rt');
%Read file into 2 separate variables
Data = textscan (fid, '%d%d', 2);
%4)Wrtie Abs. data to array
%Insert absorbance data into array
Absorbance(:,k+1) = Data {2}; %put in 2nd row of data
fclose(fid);
end
the code-error alert icon in the upper right is green, however when I run the scrip I get an "undefined function or variable 'Users' error. I tried switching the path to ~Desktop\Test and get the same error. I would appreciate if someone could explain what the proper command should be.
Thank you in advance,

Best Answer

Again, once you've got the results from dir for the files in question, then use the names as returned therein...that is, instead of
DataFiles = dir('Test_Absorbance_*.txt');
fid = fopen('Test_Absorbance_00001.txt');
which is a hardcoded filename, and there's no sense in having therefore, done the call to dir, use
fid=fopen(DataFiles(i).name,'r');
inside your loop.
Absorbance = zeros(2048, length(DataFiles)); % preallocate the two that you want to keep
Wavelength=Absorbance;
for k = 1:length(DataFiles); % this is right...begin the loop
fid=fopen(DataFiles(k).name,'r'); % open the ith file for reading
TextData = textscan(fid, '%n%n', 2048, 'delimiter', '\t');
Wavelength(:,k) = TextData{1}; % fill k-th column of preallocated
Absorbance(:,k) = TextData{2}; % arrays w/ the stuff from the file
fid=fclose(fid);
end