Main Content

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 a triangle:

b = 5;
h = 3;
a = 0.5*(b.*h)

After you save the file, you can call the script from the command line:

a =

To calculate the area of another triangle using the same script, you could update the values of b and h in the script and rerun it. Each time you run it, the script stores the result in a variable named a 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 to b and 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);

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 =
a2 =
a3 =

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 a1, a2, and a3.

Related Topics

External Websites