How can I capture the numerical output from eval()?

6 views (last 30 days)
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

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 6 Nov 2020
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;

More Answers (0)

Categories

Find more on Variables in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!