Calling a function normally vs feval

9 次查看(过去 30 天)
I have a script containing equations getting passed to lsqnonlin. Some of the equations need to call functions while they are being run like for e.g
eq(1) = x(1)^2 + 1 + f1(x(1))
eq(2) = 2x(1)^3 + x(2) + f2(x(2),x(1))
where x(1),x(2) are the variables.
I am using feval and using the function handle and passing the parameters, it's working all right. Why can't I use the normal function call like below? My exact code is below. The 2nd one is giving wrong answers. Am I missing something? P.S this isn't the code for the above equation.
eq(1) = K_1*((feval(@act1,x(2), x(6)))*(feval(@act2,x(2), x(3)))^2) - (feval(@act3,x(4),x(8),T)); %feval
%vs
eq(1) = K_2*(act2(x(2), x(6)))*(act5(x(2), x(3)))^2 - (act4(x(4),x(8),T)); %function call

回答(1 个)

Walter Roberson
Walter Roberson 2020-8-29
eq(1) = K_1*act1(x(2), x(6)) .* act2(x(2), x(3)).^2 - act3(x(4),x(8),T);
The difference between feval() and calling the function directly, is that feval() permits passing in a character vector that is the name of a function to invoke. So for example instead of the user passing in @sin the user might pass in 'sin'
Using function handles instead of character vectors is almost always preferred, but there are a couple of routines such as arrayfun() that have special code for some common functions that permits faster execution than if a function handle were used.
  2 个评论
Angshuman Podder
Angshuman Podder 2020-8-30
Thanks for your reply. Can you please tell why the 2nd formulation is giving wrong results?
Walter Roberson
Walter Roberson 2020-8-30
act1, act2, act3 in one case. act2, act4, act5 in the other case. Different functions being called.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by