MATLAB: How to capture the numerical output from eval()

evalevaluationexpressionMATLABoutput

When using "eval()" with multiple commands inside, assigning the output to a variable causes an error – which varies depending on MATLAB version.
>> c = eval('a=2;b=3;a+b')
In MATLAB R2018a and later:
Error: Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality, use '=='.
In MATLAB R2017b and earlier:
Error: The expression to the left of the equals sign is not a valid target for an assignment.
Is it possible to capture the numerical output? Namely assign "a+b" to the variable "c" in this example

Best Answer

It is not possible to assign the output of  "eval()" to a variable if the expression being evaluated contains an assignment itself. This is due to how MATLAB handles the evaluation. 
For example: 
>> c = eval('a=2;b=3;a+b')
is interpreted as
c = a = 2; b = 3; a+b
The error is due to the fact that “c = a = 2” is not a valid equation in MATLAB.
In order to capture the numerical output, you will need to call the "eval()" without assignment and then assign the answer to "c":
>> eval('a=2;b=3;a+b')
>> c = ans;