Weird behaviour in MATLAB regarding eval()

2 views (last 30 days)
Consider the following code
x = zeros(3,3);
eval(str)
g = @(x) eval(str)
g(x)
g(zeros(3,3))
MATLAB will evaluate eval(str) as intended, but complain about the other two claiming they are "Undefined functions for input arguments of type 'double'." Why?
str is a string '(unithypersphere_vector(x(:,1)).^2) + (unithypersphere_vector(x(:,2)).^2)' where unithypersphere_vector is a function defined for all vectors in R^n, and outputs a scalar.
The reason for using strings with eval is that str will change depending on user input.

Answers (2)

Jan
Jan on 25 Mar 2017
Edited: Jan on 25 Mar 2017
There must be another problem. Perhaps the function unithypersphere_vector is not defined?
Try this:
str= '((x(:,1)).^2) + ((x(:,2)).^2)'
x = zeros(3,3);
eval(str)
g = @(x) eval(str)
g(x)
g(zeros(3,3))
Works as expected in R2016b.
I guess, that you did not post a copy of the complete error message. The plural of "Undefined functions" is suspicious, because Matlab stops at the first error already. Perhaps the original message is:
Error using eval
Undefined function 'unithypersphere_vector' for input arguments of type 'double'.
?
As usual I claim, that eval is a bad choice. It looks like it causes confusing problems, as usual. Think twice if there is a better way.
  5 Comments
Jan
Jan on 25 Mar 2017
This is the effect of using the weird and evil eval. This another perfect example for the confusion this command can and will produce. Further levels of indirections will increase the problems.
I give up here. Sorry, Markus, do not take it personally. I've seen too many programmers failing with eval approachs and want to encourage you to leave this dead-end road.
Philip Borghesani
Philip Borghesani on 27 Mar 2017
Walter has the root of the problem but if you do this for the last line you are fine:
>> g=eval(['@(x) ' str])
>> g(x)
ans =
162
By creating the anonymous function with an eval you allow matlab to capture the needed variables. Take a look at the contents of the workspace returned by functions(g) in both cases.

Sign in to comment.


Walter Roberson
Walter Roberson on 26 Mar 2017
You have
g = @(x) eval(str)
when g is executing, you are within an anonymous function. The only variables visible to the anonymous function are the parameters (x in this case) and the content of the variables as of the time of the anonymous function was created -- the string '(unithypersphere_vector(x(:,1)).^2) + (unithypersphere_vector(x(:,2)).^2)' in this case. The variable unithypersphere_vector is not automatically imported to the workspace.
If you had defined unithypersphere_vector as a full function visible on the path of the anonymous function, then MATLAB would have been able to find it.

Products

Community Treasure Hunt

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

Start Hunting!