MATLAB: Eval on multi-line strings – no return value

anseval

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=25
if (a == 30)
a = 75;
else
a =42
end
37
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

to expand it a bit more. what is going on with your result = eval(string) is exactly how it is written.
you're setting everything within the string into the result which doesn't compute. so in essence you're typing (which won't work)
>> result = a=25,if (a == 30),a = 75;,else,a =42,end,37
which doesn't get you result = 37
What you could do just like you did with your fprintf statement
just do:
sprintf('a=25\nif (a == 30)\n a = 75;\nelse\n a =42\nend\n37')
eval(ans)
result = ans