Welcome to the World of Modelling and Simulation

What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ...

Discussion on MATLAB Function and Function Handle

In MATLAB, the functions and function handles (@) are used frequently, especially when writing codes in m-files. We can create many functions, but when we call a particular function, and if that function has another function inside the input parameters - the function handle (@) is the way to address and call the second function. For example, we have created a function to find the roots of a polynomial using the Newton-Raphson method and named it as 'newtonraphson'. The function input parameters are: polynomial, initial guess, error tolerance and maximum number of iterations. And the output is the roots of the polynomial.

Now, to define the polynomial, we can create another function and name it as 'polyfunction'. This function only has the polynomial, and we are interested to find its roots. Let's see how we can call the function 'newtonraphson' in MATLAB command prompt.

>> newtonraphson(@ polyfunction, 1.0, 1e-5, 100)

newtonraphson = a function for finding roots of a polynomical
@ = function handle to call another function
1.0 = Initial guess
1e-5 = Error tolerance
100 = Maximum number of iterations 

If you do not put the function handle (@) in front of the 'polyfunction', there will be an error you will see instantly in the command prompt. As you can see, a function handle is used to pass information to another function. There are other uses of the function handle in MATLAB, but the above is most frequently and widely used expression.

The aforementioned example shows the application of the function handle (@) to a known or defined function by the user (e.g. 'polyfunction'). Now, if there is an anonymous equation that we need to define in our coding, then we can also use the function handle to do the job. For example, in our program, we need to define an equation: 3x - 4y + 2z. The x, y, and z are the unknowns. To define it with the function handle, we can write as,

>> L = @ (x, y, z) (3*x - 4*y + 2*z)


L = is any parameter referring the equation
@ = function handle defining x, y, z with respect to the equation for evaluation

#MatlabFunction #FunctionHandle #PolyFunction #NewtonRaphson #Matlab #Blog #Blogger

No comments:

Post a Comment