How to add filename as a variable in MATLAB?
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!