"Code within an eval statement can unexpectedly create or assign to a variable"

From MATLAB docs, full statement:

Code within an eval statement can unexpectedly create or assign to a variable already in the current workspace, overwriting existing data.

What’s an example?

If I define function fn(); a=1 and call evalc('fn()'), could a suddenly appear in a variable scope other than inside of fn? Example here (trying to figure out the -1).

>Solution :

I think the problem that the documentation is getting at is this:

function fn()
a = 1;
eval('a = 2;');
end

In this case, it’s obvious that a will get overwritten, but it’s easy to imagine more pernicious cases where the result might not be so clear. evalin can make things worse still.

function fn2()
a = 1;
subfn2();
disp(a)
end
function subfn2()
evalin('caller', 'a = 2;');
end

Leave a Reply