Find filenames with matching ID number if they match extract data

2 views (last 30 days)
Hi I'm fairly new to MATLAB and have been struggling with this writing this code.
I have a long winded filename relating to 27 subjects and 3 visits (A-C) that is the format: Data_File_run1_SUBJECT01_typeA.csv and occasionally has Rpt_! or Rpt_2 at the end. I have a script to extract data from the files separately but I want to collate data from both 'runs'(when the files are Data_File_run1_SUBJECT01_typeA.csv and Data_File_run2_SUBJECT01_typeA.csv. I've tried using regexp but the code got messy quickly and I couldn't find an easier solution to compare the files. What I ideally want is to say if the files match load the data files and do the work.

Answers (1)

Image Analyst
Image Analyst on 30 May 2014
I'd just make a function called ParseFileName and return the run number, the subject number, and the type, and the Rpt number (which would be null if there was no Rpt for that filename).
Try this:
% Test code:
filename = 'Data_File_run1_SUBJECT01_typeA.csv'
[runNumber, subjectNumber, typeLetter, Rpt] = ParseFileName(filename)
filename = 'Data_File_run2_SUBJECT23_typeA_Rpt_3.csv'
[runNumber, subjectNumber, typeLetter, Rpt] = ParseFileName(filename)
function [runNumber, subjectNumber, typeLetter, Rpt] = ParseFileName(filename)
try
[folder, baseFileName, extension] = fileparts(filename);
% Extract parts.
if strfind(baseFileName, 'Rpt') > 1
numbers = sscanf(baseFileName, 'Data_File_run%d_SUBJECT%2d_type%c_Rpt_%d.csv')
Rpt = numbers(4)
else
numbers = sscanf(baseFileName, 'Data_File_run%d_SUBJECT%2d_type%c.csv')
Rpt = []
end
runNumber = numbers(1)
subjectNumber = numbers(2)
typeLetter = char(numbers(3))
catch ME
errorMessage = sprintf('Error in function %s() at line %d.\n\nError Message:\n%s', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
Then to compare two files, just compare the numbers and letters you get out of the function.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!