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

조회 수: 6 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2020년 11월 6일
답변: MathWorks Support Team 2020년 11월 6일
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

채택된 답변

MathWorks Support Team
MathWorks Support Team 2020년 11월 6일
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;

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by