In MATLAB, there are ways to organize and execute code, and they have different purposes and behaviors. Functions and scripts are a few of those ways.
A function contains a piece of code that performs a specific task. It accepts input arguments, processes them, and returns output arguments if required.
Variable scope: A function’s variable is local to that function and does not affect the outside workspace.
Parameters: A function can take input arguments and return them if required.
Let’s review an example of a MATLAB function and how it works.
sideLength = 5;function area = calculateSquareArea(sideLength)area = sideLength^2;endarea = calculateSquareArea(sideLength);fprintf('The area of the square with side length %.2f is %.2f\n', sideLength, area);
In the code above:
Line 1: It initializes a variable and stores its value.
Lines 3–5: It creates a function that takes an input argument.
Line 7: It calls the function and stores the value in area
.
Line 9: It prints the area
.
Scripts are sequences of MATLAB commands that are executed in order from top to bottom.
Variable scope: A script variable is stored in the MATLAB workspace and can be accessed and modified outside the script.
Parameters: There are no parameters. A script does not accept input or return output arguments. They operate on data present in the workspace.
Let’s review an example of a MATLAB script and how it works.
sideLength = 5;area = sideLength^2;fprintf('The area of the square with side length %.2f is %.2f\n', sideLength, area);
In the code above:
Line 1: It creates a variable and stores its value.
Line 3: It calculates the area of a square and stores it in a variable, area.
Line 5: It prints the area of the square.
Some of the key differences are listed below:
Function | Script |
Functions are suitable for reusable code, where we want to perform a specific task with different inputs, encapsulating logic and promoting modular design. | Scripts are suitable for quick calculations, data exploration, or automating a series of commands. |
It provide better control over input and output, allowing for more flexibility and reusability. | The script does not provide these things. |
Functions have their local workspace, which prevents unintended variable conflicts and promotes encapsulation. | Scripts operate in the context of the workspace. |
Scripts are more straightforward and suitable for simpler tasks, while functions offer more flexibility, modularity, and reusability for complex tasks.
Free Resources