I'm using R2011b. I'm trying to evaluate a string, potentially with multiple lines, and obtain a final return value.
For example:
sprintf('a=25\nif (a == 30)\n a = 75;\nelse\n a =42\nend\n37')result = eval(ans)
Produces: "Error: The expression to the left of the equals sign is not a valid target for an assignment."
For clarity, the sprintf result is:
ans =a=25if (a == 30) a = 75;else a =42end37
The error is confusing to me, as I would expect the last line of this block to return a value of 37. For example:
sprintf('37')result = eval(ans)
Creates a result variable with value of 37, as I would expect.
Further troubling me is the fact that:
sprintf('a=25\nif (a == 30)\n a = 75;\nelse\n a =42\nend\n37')eval(ans)
Executes appropriately, and even updates the ans variable to 37.. which to me implies that MATLAB kind of knows there is a return value for this code block. Thus this adds to my confusion as to why I can't override the assignment to ans with a new variable… it's like, it's too late if you are evaling a multi-line block, but not a single line expression.
Can anyone explain the fault in my expectations here?
thanks!
Best Answer