Subfunction example in Matlab programming language | applied electronics engineering


Subfunction example in Matlab programming language

By Applied Electronics - Friday, March 17, 2017 No Comments
Here we show you how to implement sub-function in Matlab programming language. sub-function is usual matlab function which is implemented within another Matlab function. There is no special keyword required for creating matlab subfunction. To create a sub-function you would create first a function and within it you would create another function and this function is called subfunction. The subfunction is local to the primary function and its outputs are not available in Matlab local workspace. This is also called scoping.

As an example of subfunction consider that we want to create a function that gives us the roots of a quadratic equation. Let the roots be called r1 and r2 and the quadratic equation variable be a, b and c.

Here is an example of primary function called quadsolve and a subfunction called discrim to solve the quadratic equation.

function [r1,r2] = quadsolve(a,b,c)
d = discrim(a,b,c);
r1 = (-b + d) / (2*a);
r2 = (-b - d) / (2*a);
function D = discrim(a,b,c)
D = sqrt(bˆ2 - 4*a*c);

Here the sub function discrim has output D.

See also MATLAB function to obtain the roots of the quadratic equation.


No Comment to " Subfunction example in Matlab programming language "