MATLAB: Does the code not work correctly if I use the EVAL, ASSIGNIN or LOAD function to create a workspace variable that has the same name as a MATLAB function

assignincreateevalfunctionMATLABnamesamevariable

I have a MATLAB function that uses the EVAL command to create a variable in the workspace. The variable being created has the same name as a MATLAB function. When I try to use the variable later, MATLAB instead tries to call the function with the same name. For example:
function test
a = 1;
b = 2;
c = 3;
names = {'a','b','c'};
for idx = 1:length(names)
eval(['sum.', names{idx}, '=', names{idx}, ';'])
end
exist('sum')
sum
When I run this code, the EXIST function properly returns 1, indicating that "sum" is a variable. However, when I try to display the value of "sum" on the last line of the file, I receive the following error:
??? Error using ==> sum
Not enough input arguments.

Best Answer

This is a limitation of MATLAB when the EVAL function (and related functions such as ASSIGNIN, LOAD) is used to create workspace variables that have the same name as a MATLAB function. The MATLAB Interpreter attempts to determine if an identifier represents a function name at parse time, and if so, binds to that function. This allows for a substantial performance improvement, but introduces some limitations. Because the MATLAB Interpreter cannot determine what variables an EVAL statement will create, it ends up binding "sum" to the SUM function in the example below:
function test
a = 1;
b = 2;
c = 3;
names = {'a','b','c'};
for idx = 1:length(names)
eval(['sum.', names{idx}, '=', names{idx}, ';'])
end
exist('sum')
sum
One way to work around this limitation is to move the assignment outside of the EVAL function. For example:
function test
a = 1;
b = 2;
c = 3;
names = {'a','b','c'};
for idx = 1:length(names)
sum.(names{idx}) = eval(names{idx});
end
exist('sum')
sum
Another workaround is to initialize the variable at the onset:
function test
a = 1;
b = 2;
c = 3;
sum = 0;
names = {'a','b','c'};
for idx = 1:length(names)
eval(['sum.', names{idx}, '=', names{idx}, ';'])
end
exist('sum')
sum