MATLAB: Import .csv Data and assemble structure array

csvdata importlogfile

Hey everyone!
I have a folder with a lots of .csv data, always with the same pattern (just changing ID-number):
logfile_11111_accelerationX.csv, logfile_11111_accelerationY.csv,…,logfile_11111_speed.csv
logfile_22222_accelerationX.csv, logfile_22222_accelerationY.csv,…,logfile_22222_speed.csv
I also have a meta file where all those ID-numbers (11111,22222,…) are specified.
What I want to do is to write a function which assembles all the .csv-Data with the same ID-number to one .mat struct, e.g. logData11111, where all data is included, e.g. logData11111.accelerationX, logData11111.speed, and so on.
Does someone have an idea how to do this?
Thanks in advance!

Best Answer

First list all files in your directory. This will get you started:
dirContent = dir('C:\Users\blah\blah\blah');
contentList = {dirContent.name};
Then loop through each file ID number and use regexp or strfind to identify matching files.
fileIDs = {'1111', '2222', '3333'}; %from your meta file
for i = 1:length(fileIDs)
matches = regexp(contentList, sprintf('%s*.csv', fileIDs{i}), 'match');
selectedFiles = matches{~cellfun(@isempty, matches)};
% Now you can import data from selectedFiles{:} here
end
My code assumes your fileIDs will be strings; if that's not the case you'll need to make small changes. You may also need to adapt the regular expression to your filenames. This has not been tested and represents a basic method you'll likely need to adapt to your needs.