MATLAB: How to use assignin and eval together in function

assignincomplexdynamic variable namesevalevilfunctionMATLABslow

I have a script that I am trying to turn into a function. The reason being is that I have multiple projects (with individual file folders) that I use the same script for processing. Rather than copying the script from folder to folder and ensuring I am using the latest one version, I'd prefer to simply create and call majority of it as a function.
My issue is my script loads a mat file (with hundreds of variables) and a text file (i.e., tab) that contains the variables names. The code reads the text file row by row and processes the variables listed in each row.
Below are some example rows of tab:
0280;3000;433203.10;100163.60;116.51;SM001_200209;SM001_200304;SM001_201705;SM001_201810;SM001_201497;
0068;3600;433459.90;099725.55;123.29;SM002_200209;SM002_200304;SM002_201705;SM002_201810;SM002_201497;
My issues is I currently use assignin and eval together in my function (I later use the name variable in my code), but they will not work in my script.
for count = 1:size(tab,1)
temp = tab(count,38:end);
try
assignin('base','name',eval(['[' strrep(temp,' ',';') ']']));
name;
catch %#ok<CTCH>
disp('! Wrong variable(s) name or format !')
end
end
I have tried changing the 'base' to 'caller' but it still fails.
I know using assignin and eval is frowned upon, but this script serves my purpose.
Is there any way to get the above to work in a function?

Best Answer

Your code concept forces you to write slow, complex, obfuscated, buggy, and hard to debug code:
You can easily avoid your bad code design by simply loading into an output variable (which is a structure):
and using dynamic fieldnames:
An outline of what you should do:
V = {varnames in a cell array}; % one row of names file
S = load(...,V{:});
N = numel(V);
C = cell(1,N);
for k = 1:N
C{k} = S.(V{k});
end
... "combine" your data here, e.g.:
data = horzcat(C{:})
and then, if you put this inside a function, simply return that data as an output argument (which is much more efficient and less buggy that assignin).
Related Question