This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

Scripts vs. Functions

This topic discusses the differences between scripts and functions, and shows how to convert a script to a function.

Program files can be scripts that simply execute a series of MATLAB® statements, or they can be functions that also accept input arguments and produce output. Both scripts and functions contain MATLAB code, and both are stored in text files with a .m extension. However, functions are more flexible and more easily extensible.

For example, 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 program 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 Examples

More About

Was this topic helpful?