Calling a function normally vs feval

조회 수: 10 (최근 30일)
Angshuman Podder
Angshuman Podder 2020년 8월 29일
댓글: Walter Roberson 2020년 8월 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