How can I capture the numerical output from eval()?
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 6 Nov 2020
Réponse apportée : MathWorks Support Team
le 6 Nov 2020
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
Réponse acceptée
MathWorks Support Team
le 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;
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Variables dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!