Scripts vs. Functions
This topic discusses the differences between scripts and functions, and shows how to convert a script to a function.
Both scripts and functions allow you to reuse sequences of commands by storing them in code files. Scripts are the simplest type of code file, since they store commands exactly as you would type them at the command line. However, functions are more flexible and more easily extensible.
Create a script in a file named
triarea.m that computes the area of
b = 5; h = 3; a = 0.5*(b.*h)
After you save the file, you can call the script from the command line:
a = 7.5000
To calculate the area of another triangle using the same script, you could update the
h in the script and rerun it. Each
time you run it, the script stores the result in a variable named
that is in the base workspace.
However, instead of manually updating the script each time, you can make your code
more flexible by converting it to a function. Replace the statements that assign values
h with a function declaration statement.
The declaration includes the
function keyword, the names of input and
output arguments, and the name of the function.
function a = triarea(b,h) a = 0.5*(b.*h); end
After you save the file, you can call the function with different base and height values from the command line without modifying the script:
a1 = triarea(1,5) a2 = triarea(2,10) a3 = triarea(3,6)
a1 = 2.5000 a2 = 10 a3 = 9
Functions have their own workspace, separate from the base workspace. Therefore, none
of the calls to the function
triarea overwrite the value of
a in the base workspace. Instead, the function assigns the
results to variables