How to add filename as a variable in MATLAB?

3 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2020-11-25
编辑:Walter Roberson 2020-11-25
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by