eval vz feval, different results

8 views (last 30 days)
Zdenek Vesely
Zdenek Vesely on 6 Oct 2017
Commented: Stephen23 on 24 Oct 2017
Hi. I would like to ask, when using feval and eval, the result is different? I thing, that I'm using same approach. Thank you!
%F = some symbolic function with this symbolic: n1i,n2i,n3i,n4i,n5i,n6i,n7i
f = matlabFunction(F); % in my case: f = @(x)f(x(1),x(2),x(3),x(4),x(5),x(6),x(7))
Xa = [0.1000 0.1000 0.1000 0.1000 0.1000 0.1000 0.1000] %for example some real value
%approach1--------------
fa=feval(f,Xa)
-0,00430563198070900 + 0,00000000000000i
-0,00358093388632469 + 0,00000000000000i
-0,00313919755488547 + 0,00000000000000i
-0,00338161000029060 + 0,00000000000000i
-0,00799484623495874 + 0,00000000000000i
-0,00277875928862729 + 0,00000000000000i
-0,00410906741467898 + 2,22648608470585e-06i
%approach2-------------
fa_0=subs(F,{n1i,n2i,n3i,n4i,n5i,n6i,n7i},{Xa(1),Xa(2),Xa(3),Xa(4),Xa(5),Xa(6),Xa(7)})
fa=eval(fa_0)
-0,00430563198070900
-0,00358093388632500
-0,00313919755488500
-0,00338161000029100
-0,00799484623495900
-0,00277875928862700
-0,00409570849817100
  1 Comment
Stephen23
Stephen23 on 24 Oct 2017
Why is eval required at all? Surely subs and double would be enough?

Sign in to comment.

Answers (1)

Rik
Rik on 24 Oct 2017
The reason would depend on a slightly different method of calculation and rounding. I don't think the exact difference is really relevant, because you should use neither. Use this instead:
fa=f(Xa);
Stephen Cobeldick is very pasionate about this topic (and with good reason), so I have taken the liberty of adapting some of his thoughts on this topic: Introspective programing (eval and other functions like it) is slow, and the MATLAB documentation warns specifically against it. Using eval is slow, makes debugging difficult, and removes all code helper tools (code checking, syntax hints, code completion, variable highlighting, etc.). A longer discussion can be found here. If you are not an expert and you think you need eval, there are probably better solutions to your problem.

Categories

Find more on Code Execution in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!