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 Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by