MATLAB Answers


Using 'assignin' to assign value to variable 'max'

Asked by Cody Patterson on 17 Sep 2019
Latest activity Commented on by Cody Patterson on 17 Sep 2019
I'm using the 'assignin' function to assign a value to the variable 'max' using the code below:
function get_data
function assign_value
If I run 'get_data' from the command line, I get an error that I'm not passing enough input arguments to 'max,' since 'max' is a built-in function to MATLAB.
Interestingly, I can add the output 'max' to the function 'get_data' by writing
function max=get_data
and the function will run and display the value '5'.
My questions are:
1) Is this how 'assignin' is supposed to behave, i.e. does it not assign a value to a variable if the variable name is an instrinsic function in MATLAB?
2) Why is 'assignin' not able to assign value to 'max,' but I can execute 'max=5' in other contexts and MATLAB won't complain?


Sign in to comment.




1 Answer

Answer by Guillaume
on 17 Sep 2019
 Accepted Answer

First and foremost, you shouldn't be using assignin and its friends (evalin, etc.). There's always better ways to do whatever you're trying to do. Also, you shouldn't call a variable max (or mean or sum or size or one of the oft used functions). The two together is really asking for trouble!
As to the behaviour you see, it is expected in recent versions of matlab. Matlab has a just in time compiler that optimises functions so they run faster. One decision the compiler must make before the code is run is whether something is a function call or a variable. In recent versions if it doesn't see an assignment to the something, it assumes it's a function. Anything that pops variables into existence break that assumption and it's documented (at least in the release notes) that it's no longer supported in recent versions. You'd have the same problem with a plain load or eval.
The workaround is to create the variable first:
function get_data
max = []; %now the JIT compiler knows that max is a variable (a badly named variable!)
The better work around of course is to define the variable as an output of assign_value:
function get_data
my_max = assign_value; %and don't use max as a variable name
function out = assign_value;
out = 5;
It's simpler code as well. What's not to like?

  1 Comment

Thank you for the clear explanation on this! I agree that assignin is not always the best tool to get the job done, and for this toy example, I would code it the same way as your second example. I would also not name a variable 'max.' My original problem showed up when naming a variable 'pe' which also happens to be a built-in function. However, I am automating data to be read in from fortran with the same variable names as fortran source code. I think assignin is necessary for this sort of task. If you know of otherways, I would like to hear them.

Sign in to comment.