Introduction to Matlab
MATLAB: Script Files
This tutorial introduces creating, running, and modifying MATLAB scripts. You will also practise using loops and conditional statements.
1. What is a script?
A MATLAB script is a file containing a sequence of commands. When you run the script, MATLAB executes these commands in order. Scripts allow you to save, repeat, and modify calculations without retyping commands in the Command Window.
In this tutorial, you will work with plain-text scripts saved with
the .m extension.
When naming a script:
- Start the name with a letter.
- Use letters, digits, and underscores.
- Avoid spaces and arithmetic symbols such as
+or-. - Avoid names of built-in functions, such as
plot.morsin.m.
For example, sine_plot.m is a suitable filename.
Use % to add comments explaining your code.
A semicolon ; at the end of a statement suppresses its output
in the Command Window; the statement is still executed.
2. Creating and running a script
- Select New Script in MATLAB to open the Editor.
- Enter the code shown below.
- Save the file as
sine_plot.min your current MATLAB folder. - Click Run in the Editor.
% Plot the sine function over the interval [0, 2*pi]
x = 0:pi/100:2*pi;
y = sin(x);
figure;
plot(x, y);
xlim([0 2*pi]);
xlabel('x [rad]');
ylabel('sin(x)');
title('Sine function', 'FontSize', 12);
grid on;
The script defines the values of x, calculates the corresponding
values of sin(x), and displays a labelled plot.
You can also run the script by typing its name, without the
.m extension, in the Command Window:
sine_plot
For this method, the file must be in the current folder or in a folder on the MATLAB search path.
>> in a script.
3. Editing a script
Open an existing script in the MATLAB Editor, modify the required commands, save the file, and run it again.
To change the previous example from a sine plot to a cosine plot:
- Replace
y = sin(x);withy = cos(x);. - Change the vertical-axis label to
cos(x). - Change the title to
Cosine function. - Save the modified script as
cosine_plot.mto preserve the original example.
Remember to update labels and comments whenever you change the calculations.
Example: modifying matrix calculations
Scripts can also be used to repeat matrix calculations with different input data:
% Define a scalar and a 3-by-3 matrix
a1 = 5.5;
B = [1 4 17; 20 0 5; 4 9 11];
% Calculate a1 multiplied by the inverse of B
C = a1 * B^-1
Here, B^-1 denotes the matrix inverse, not the reciprocal
of each element. The matrix must be nonsingular.
The result C is displayed because the last statement
does not end with a semicolon.
Replace the definition of B with:
B = [1 4 22; 20 23 5; 54 9 11];
Save and rerun the script. Compare the new matrix C
with the previous result.
B*u = f, use
u = B\f rather than explicitly calculating the inverse.
4. Repeating calculations: the for loop
A for loop repeats a set of commands for successive values
of an index. The following example calculates the first ten positive
integer powers of 2:
% Allocate space for ten results
A = zeros(1, 10);
% Calculate successive powers of 2
for n = 1:10
A(n) = 2^n;
end
disp(A);
The index n takes the values 1 through 10.
During each iteration, the result is stored in the corresponding element
of A. The keyword end closes the loop.
Expected output:
2 4 8 16 32 64 128 256 512 1024
5. Selecting calculations: the if–else statement
An if–else statement selects which commands to execute
depending on whether a condition is true.
The following script evaluates a function using one expression for
x <= 20 and another for x > 20:
x = 1:50;
y = zeros(size(x));
for k = 1:length(x)
if x(k) <= 20
y(k) = 2*x(k) + 5;
else
y(k) = -x(k) + 65;
end
end
figure;
plot(x, y, 'LineWidth', 1.5);
xlabel('x');
ylabel('y');
title('Piecewise-defined function');
grid on;
The first end closes the conditional statement;
the second closes the loop. Indentation helps make this structure clear.
Here, k is the array index, while x(k)
is the corresponding argument of the function.
6. Practice tasks
- Create and run
sine_plot.m. - Save a modified version as
cosine_plot.mand update the labels and title. - Modify the loop example to calculate the first ten positive integer powers of 3.
- Run the piecewise-function example and check the calculated values at
x = 20andx = 21. - Explain the purpose of
%,;,for,if,else, andend.
6. Formatting and exporting plots
A figure prepared for a report should have readable axis labels, appropriate axis limits, and sufficient image resolution. The following examples show how to control these properties in a script.
6.1. Adding axis labels and a title
Run this example to create a plot. Use xlabel and
ylabel to describe the axes, including units where appropriate.
Use title to add a title.
x = 0:pi/100:2*pi;
y = sin(x);
figure;
plot(x, y, 'b-', 'LineWidth', 1.5);
xlabel('x [rad]', 'FontSize', 12);
ylabel('sin(x) [-]', 'FontSize', 12);
title('Sine function', 'FontSize', 14);
set(gca, 'FontName', 'Arial', 'FontSize', 12);
grid on;
box on;
gcf refers to the current figure, while gca
refers to the current axes. A figure can contain several axes,
for example when using subplot.
6.2. Changing axis limits
Set the horizontal and vertical ranges separately using
xlim and ylim:
xlim([0 2*pi]);
ylim([-1.2 1.2]);
Alternatively, set both ranges with one command.
The order is [xmin xmax ymin ymax]:
axis([0 2*pi -1.2 1.2]);
Narrower limits display a selected part of the data; wider limits add space around the curve. For example:
% Display only part of the curve
xlim([pi/2 3*pi/2]);
% Extend the displayed range beyond the data
xlim([-0.5 2*pi+0.5]);
ylim([-1.5 1.5]);
These commands change the displayed region without modifying or deleting the underlying data.
The following commands are alternatives for automatic adjustment. Run the one that gives the required result:
axis tight; % Fit the axis limits to the data range
axis padded; % Add a small margin around the data
axis auto; % Restore automatic axis limits
Tick positions can also be specified explicitly:
set(gca, 'YTick', -1:0.5:1);
6.3. Changing the figure size and plotting area
The figure size and the axis limits are independent. Resizing the figure changes its layout, not the range of data. For a separate figure window, specify its position and size in pixels:
set(gcf, 'WindowStyle', 'normal');
set(gcf, 'Units', 'pixels');
set(gcf, 'Position', [100 100 900 450]);
The four values are [left bottom width height].
In this example, the figure is 900 pixels wide and 450 pixels high.
These on-screen dimensions do not necessarily equal the dimensions
of the exported PNG.
To adjust the plotting area within the figure, change the axes position:
set(gca, 'Units', 'normalized');
set(gca, 'Position', [0.12 0.18 0.83 0.72]);
Here, [left bottom width height] is expressed as fractions
of the parent container dimensions. Increasing the width or height
enlarges the plotting area and reduces the space available for labels.
Leave sufficient room for axis labels, tick labels, and the title.
6.4. Saving a PNG file and setting its resolution
In MATLAB R2020a or later, use exportgraphics to export
the current axes, including their labels and title:
exportgraphics(gca, 'sine_plot.png', ...
'Resolution', 300, 'BackgroundColor', 'white');
The file is saved in the current folder unless a different path is
specified. The value 300 sets the resolution to 300 dots
per inch (DPI). At the same physical size, increasing DPI increases
the number of image pixels and usually the file size.
It does not improve the accuracy of the plotted data.
An alternative, also available in older MATLAB versions, is
print. This exports the figure:
set(gcf, 'Color', 'white');
set(gcf, 'PaperPositionMode', 'auto');
print(gcf, 'sine_plot.png', '-dpng', '-r300');
-dpngselects the PNG format.-r300selects 300 DPI; use-r150for 150 DPI.PaperPositionModeset toautobases the printed size on the figure size.
To control the physical output size explicitly with print,
set the paper position in inches:
set(gcf, 'PaperUnits', 'inches');
set(gcf, 'PaperPosition', [0 0 6 3]);
set(gcf, 'PaperPositionMode', 'manual');
print(gcf, 'sine_plot_1800x900.png', '-dpng', '-r300');
A 6-by-3-inch image exported at 300 DPI has dimensions of 1800 by 900 pixels.
6.5. Cropping or extending the outer margins
Cropping the outer margins removes unnecessary blank space around
the plot. This is different from changing the axis limits.
By default, exportgraphics exports a tightly cropped
plot while retaining its labels and title.
In locally installed MATLAB R2025a or later, the
Padding option provides additional control.
The following examples are alternatives:
% Crop unnecessary outer whitespace
exportgraphics(gca, 'plot_tight.png', ...
'Resolution', 300, 'Padding', 'tight');
% Add a 20-pixel outer margin
exportgraphics(gca, 'plot_margin.png', ...
'Resolution', 300, 'Units', 'pixels', 'Padding', 20);
% Preserve the relative margins shown in the figure
exportgraphics(gca, 'plot_figure_margins.png', ...
'Resolution', 300, 'Padding', 'figure');
6.6. Complete example
This script creates a labelled plot, sets its dimensions and axis limits, and saves it as a PNG file at 300 DPI. It requires MATLAB R2020a or later.
% Input data
x = 0:pi/100:2*pi;
y = sin(x);
% Create a figure and axes
fig = figure('Color', 'white', 'WindowStyle', 'normal');
set(fig, 'Units', 'pixels', 'Position', [100 100 900 450]);
ax = axes('Parent', fig);
% Draw and format the curve
plot(ax, x, y, 'b-', 'LineWidth', 1.5);
xlabel(ax, 'x [rad]', 'FontSize', 12);
ylabel(ax, 'sin(x) [-]', 'FontSize', 12);
title(ax, 'Sine function', 'FontSize', 14);
set(ax, 'FontName', 'Arial', 'FontSize', 12);
set(ax, 'Units', 'normalized', ...
'Position', [0.12 0.18 0.83 0.72]);
xlim(ax, [0 2*pi]);
ylim(ax, [-1.2 1.2]);
grid(ax, 'on');
box(ax, 'on');
% Export the axes, labels, and title
exportgraphics(ax, 'sine_plot.png', ...
'Resolution', 300, 'BackgroundColor', 'white');
Practice:
Export the same plot at 150 and 300 DPI. Compare the pixel dimensions,
file sizes, and appearance when enlarged. Then change the horizontal
limits to [0 pi] and save the result under a different name.