MATLAB: Reading in txt data files with changing names

MATLABregexptext file

Hello there!
Currently I have some code that reads in various numbered test data files to do fluids calculations later. Originally these files were created as 'test # 1200.001' 'test # 1200.002' for 10 files per test. I would read the txt file names from the input directory to then create appropriately titled output folder where calculations and graph go. However now I encounter some test names like 'test # 1200b' for any [a-z]. I modified some of my code and it works with reading any test file name as such now. However I get an error which involves the sprintf() command trying to create the output folder name for the user to select. I was wondering if theres a way to include letter characters after the '# %d' in the sprintf()? Or do I need a different command (note this does work when its just # 1400, its when it becomes # 1400b)?
I have included the portion of my code up to where it fails.
clear all;
%Default input dir , output dir
indir = 'C:\Lab\Tests';
outdir = 'C:\Tdata';
inputdir = dir('C:\Lab\Tests');
inputdir =(strncmp({inputdir.name}, '.', 1)) = []; %removes files from Windows
[igno,newvar] = max([inputdir.datenum]); %select most recent test date fldr
inputdir = inputdir(newvar).name;
folder = uigetdir([indir '\' inputdir], 'Select Source Data Folder');
[filepath, name] = fileparts(folder);
findNumb1 = ~isempty(regexp(name, '\d{4}$','match'));
findNumb2 = ~isempty(regexp(name, '\d{4}[a-z]', 'match')); % changed to a if/elseif loop to check if file does or not have letter after test number
if findNumb1
findNumb = regexp(name, '\d{4}', 'match');
cell2char = findNumb{1};
fileNumber = str2num(cell2char);
elseif findNumb2
findNumb = regexp(name, '\d{4}[a-z]', 'match');
cell2char = findNumb{1};
fileNumber = str2num(cell2char);
end
%%% Below is where I believe the fix should be
foldername = sprintf('test # %d', fileNumber); %<<<<<<<<here?
subfolder = 'CHANNEL';
fileselectfortime = sprintf('test # %d.001', fileNumber);
filename = fullfile(indir,foldername,subfolder,fileselectfortime);
fid = fopen(filename,'r');
C = textscan(fid, '%s%s%s%f', 'delimiter', '\n', 'Headerlines', 25);
class(C);
Cre = reshape(C, [4 1]);
empty = cellfun(@isempty, Cre);
Cre(empty) = [];
fclose(fid);

Best Answer

Based on the file name type, you should form the "foldername" and "fileselectfortime".
You can modify your code as shown below:
if findNumb1
findNumb = regexp(name, '\d{4}', 'match');
cell2char = findNumb{1};
fileNumber = str2num(cell2char);
foldername = sprintf('test # %d', fileNumber);
fileselectfortime = sprintf('test # %d.001', fileNumber);
elseif findNumb2
findNumb = regexp(name, '\d{4}[a-z]', 'match');
cell2char = findNumb{1}; % cell2char = 1400b
fileNumber = str2num(cell2char(1:end-1)); % 1400
foldername = sprintf('test # %s', cell2char); % 'test # 1400b'
fileselectfortime = sprintf('test # %d.001%s', fileNumber, cell2char(end)); % 'test # 1400.001b'
end
Hope this helps!