How to add filename as a variable in MATLAB?

3 views (last 30 days)
I have a folder of 1000 .mat files which each of these .mat files is a structure of two fields DH12 and HRF. My aim is to create a csv file that has three columns SubjectID, DH12, HRF. Subjects IDs are the same as the .mat files names that could be extracted by sprintf(name) based on the code below. The output of this loop gives me a table of two columns DH12 and HRF, how can I add the subject ID as a column based on the filenames.
files = dir('*.mat')
for i = 1:numel(files)
mat_filename = fullfile(files(i).folder, files(i).name);
[~, name] = fileparts(files(i).name);
csv_filename = fullfile(files(i).folder, [name '.csv']);
data = load(mat_filename);
X = data.params.f.DH12;
Y = data.params.f.HRF;
Z = horzcat(X,Y);
colNames = {'DH12','HRF'};
sTable(i,:)= array2table(Z,'VariableNames',colNames)
end

Accepted Answer

Walter Roberson
Walter Roberson on 25 Nov 2020
Edited: Walter Roberson on 25 Nov 2020
files = dir('*.mat');
numFiles = numel(files);
sTables = table();
for i = 1:numFiles
mat_filename = fullfile(files(i).folder, files(i).name);
[~, name] = fileparts(files(i).name);
csv_filename = fullfile(files(i).folder, [name '.csv']);
data = load(mat_filename);
X = data.params.f.DH12;
Y = data.params.f.HRF;
colNames = {'DH12','HRF'};
sTable = table(X, Y, 'VariableNames', colNames);
[~, sid, ~] = fileparts(csv_filename);
sTable.SubjectID(1:height(sTable)) = {sid};
sTables = [sTables; sTable];
end
  3 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!