Recently I found a problem in matlab code when calling assignin('caller',...)
in a function to make new variables in the caller function, if the variable name is the same name as a matlab function name in the path.
Here is a simple code snippet just to demonstrate the problem.
function myfunctest
sin = 0;
subfcn_set; % call subfcn_set to make a new variable
whos % list variables in current workspace
sin % raise error because it calls the sin function
end
function subfcn_set
assignin('caller', 'sin', 'I am sine');
end
save the snippet into myfunctest.m
and run it in matlab
>> myfunctest
Name Size Bytes Class Attributes
sin 1x9 18 char
sin =
I am sine
Everything looks good. But if I delete sin = 0
in myfunctest
and run it again,
>> myfunctest
Name Size Bytes Class Attributes
sin 1x9 18 char
Error using sin
Not enough input arguments.
Error in myfunctest (line 8)
sin
The builtin sin
function is called even if the the variable sin
existed as indicated by whos
. This applies to other matlab function names in the path too.
If we change the variable name from sin
to some other thing, e.g., notafunc
, everything looks good regardless the initialization.
>> myfunctest
Name Size Bytes Class Attributes
notafunc 1x13 26 char
notafunc =
I am notafunc