MATLAB: Removing loaded variables from workspace after changing name with eval

anti-patternevalevilremove from workspace

Hi,
I have a large data set, where each filename goes as XX001 etc. each filename is also the name of the stuct in the workspace.
so i use eval to rename it:
DataFiles = dir('C:\MyFolderPath');
for i = 1:length(DataFiles)
SubjectName = DataFiles(i).name;
load(SubjectName); eval(['patient', ' = ', SubjectName, ';'])
end
since i want my code to fit all the data, i change the names.
but then, i'm left with the original file name in the workspace.
how can i delete it?
Thank you!

Best Answer

Do NOT use eval for such trivial tasks as importing data.
Either access the fieldname, e.g.
S = dir('C:\MyFolderPath');
N = numel(S);
for k = 1:N
F = S(k).name;
T = load(F);
patient = T.(F);
end
Or use a cell array (this assumes exactly one variable per mat file):
for k = 1:N
F = S(k).name;
C = struct2cell(load(F));
patient = C{1};
end
See also: