How to pass (a custom) function as an argument to another function in MATLAB
If we write an integral universal program that wants to make it more versatile, we can use the integrand as a parameter as well. The function pointer can be used to implement the function of the top, and how to do it in MATLAB? Using a function handle--a function similar to a function pointer.
If we have now written a Simpson method integral function as follows, we will pass the function as an argument (of course, MATLAB has already provided us with a very cow x integral function, here is just an example):
function G=myintegrate (f,n,a,b)
%integration using Simpson method
N=N/2;
H= (b-a)/n;
X=a:h:b;
Fv=f (x);
S=sum (FV (1:2:2*n-1));
S=s+sum (FV (2:2:2*n)) * *;
S=s+f (a) +f (b);
S=S*H/3;
G=s;
Now the job is to replace the F-function above with whatever function we want.
To define a function handle:
[Email protected] functionname
You can then pass the handle as a parameter to the above function (or any other function that needs to use the function as a parameter).
For example, if you are integrating sin (x) on 0~PI/2, you can enter the following:
>>[email protected];
>>myintegrate (FH,100,0,PI)
Ans =
0.9947
Function handles can be specified as arbitrary MATLAB functions-including, of course, our own custom functions, such as the following functions defined in the MYFUN.M file:
function F=myfun (x)
F=x;
So
>>[email protected];
>>myintegrate (fh2,100,0,1)
Ans =
0.4967
How to pass (a custom) function as an argument to another function in MATLAB