Search code examples
matlabnamespacesworkspace

variable namespace in matlab


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

Solution

  • This is actually not a "problem". From the documentation of assignin:

    assignin(ws, 'var', val) assigns the value val to the variable var in the workspace ws. The var input must be the array name only; it cannot contain array indices. If var does not exist in the specified workspace, assignin creates it.

    Since there is a function sin() existing in the namespace matlab does not create the variable.

    Apart from this I would not recommend this approach since it will confuse other persons using your code. In case you do not know that this line exists, you will not realize what happens. An exception can be made for subfunctions to other functions, in case the subfunctions are defined in the same .m file as the function using the subfunctions. However, even then it should be used sparsely in case the file is large.