MATLAB: How to programatically make workspace variable name same as the .mat file name loaded into Matlab

load.mat fileMATLABvariable nameworkspace name

I have a number of .mat files in a folder called m2.mat, m3.mat, m4.mat and so on all the way to m400.mat. When each .mat file is loaded into Matlab, the associated workspace variable has a different name. For example, m2.mat has a workspace name as data_run_2, and m3.mat has a workspace name as data_run_3. I would like all worspace variables to have the same name as the .mat file name, thus m2.mat would have the workspace name m2. Is there a way to programatically perform this operation for all of the 400 files?
Thanks so much for the assistance!

Best Answer

A much better approach than awful dynamic variable names is to use simple, efficient indexing, e.g.:
D = 'path to the directory where the files are saved';
S = dir(fullfile(D,'*.mat'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
C = struct2cell(load(F));
S(k).data = C{1}; % assumes exactly ONE variable per file
end
All of the data will be stored in the structure S:
Related Question