MATLAB code can be saved in m-files to be reused. m-files have the .m
extension which is automatically associated with MATLAB. An m-file can contain either a script or functions.
Scripts
Scripts are simply program files that execute a series of MATLAB commands in a predefined order.
Scripts do not accept input, nor do scripts return output. Functionally, scripts are equivalent to typing commands directly into the MATLAB command window and being able to replay them.
An example of a script:
length = 10;
width = 3;
area = length * width;
This script will define length
, width
, and area
in the current workspace with the value 10
, 3
, and 30
respectively.
As stated before, the above script is functionally equivalent to typing the same commands directly into the command window.
>> length = 10;
>> width = 3;
>> area = length * width;
Functions
Functions, when compared to scripts, are much more flexible and extensible. Unlike scripts, functions can accept input and return output to the caller. A function has its own workspace, this means that internal operations of the functions will not change the variables from the caller.
All functions are defined with the same header format:
function [output] = myFunctionName(input)
The function
keyword begins every function header. The list of outputs follows. The list of outputs can also be a comma separated list of variables to return.
function [a, b, c] = myFunctionName(input)
Next is the name of the function that will be used for calling. This is generally the same name as the filename. For example, we would save this function as myFunctionName.m
.
Following the function name is the list of inputs. Like the outputs, this can also be a comma separated list.
function [a, b, c] = myFunctionName(x, y, z)
We can rewrite the example script from before as a reusable function like the following:
function [area] = calcRecArea(length, width)
area = length * width;
end
We can call functions from other functions, or even from script files. Here is an example of our above function being used in a script file.
l = 100;
w = 20;
a = calcRecArea(l, w);
As before, we create l
, w
, and a
in the workspace with the values of 100
, 20
, and 2000
respectively.