08 - MATLAB - Functions
08 - MATLAB - Functions
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2
You can call the above function from command prompt as −
quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Private Functions
A private function is a primary function that is visible only to a limited group of other
functions. If you do not want to expose the implementation of a function(s), you can
create them as private functions.
Private functions reside in subfolders with the special name private.
They are visible only to functions in the parent folder.
Example
Let us rewrite the quadratic function. This time, however, the disc function calculating
the discriminant, will be a private function.
Create a subfolder named private in working directory. Store the following function
file disc.m in it −
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function
Create a function quadratic3.m in your working directory and type the following code
in it −
function [x1,x2] = quadratic3(a,b,c)
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic3
You can call the above function from command prompt as −
quadratic3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Global Variables
Global variables can be shared by more than one function. For this, you need to
declare the variable as global in all the functions.
If you want to access that variable from the base workspace, then declare the variable
at the command line.
The global declaration must occur before the variable is actually used in a function. It
is a good practice to use capital letters for the names of global variables to distinguish
them from other variables.
Example
Let us create a function file named average.m and type the following code in it −
function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end
Create a script file and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result −
av = 35.500