Filter löschen
Filter löschen

Calling a function normally vs feval

7 Ansichten (letzte 30 Tage)
Angshuman Podder
Angshuman Podder am 29 Aug. 2020
Kommentiert: Walter Roberson am 30 Aug. 2020
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

Antworten (1)

Walter Roberson
Walter Roberson am 29 Aug. 2020
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 Kommentare
Angshuman Podder
Angshuman Podder am 30 Aug. 2020
Thanks for your reply. Can you please tell why the 2nd formulation is giving wrong results?
Walter Roberson
Walter Roberson am 30 Aug. 2020
act1, act2, act3 in one case. act2, act4, act5 in the other case. Different functions being called.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by