How to pass (a custom) function as an argument to another function in MATLAB

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.