MNTC MATLAB Reference Sheet
Page 1
Loops
Creating matrices
Colons:
1:N = 1, 2, ... N
5:2:11 = 5, 7, 9, 11
linspace:
linspace(0, 20) - 100 evenly spaced points from
0 to 20
linspace(0, 20, 500) - 500 evenly spaced points
for (i = 1:10)
...
end
Graphing
Basic line graph.
x = linspace(-2, 2);
A = zeros(r, c) - r × c matrix, all zeros
y = sin(x);
A = ones(r, c) - r × c matrix, all ones
plot(x, y);
A = ones(r, 1) - r-long column vector, all ones
Plotting data as dots.
plot(x, y, ’.’);
Accessing, Modifying Matrices
Plotting line in red.
V = 2:2:10 - 5 element vector, “2,4,6,8,10”
plot(x, y, ’r’);
V(3) - 3rd element of V (“6”)
Plotting dots in green.
V(end) - gives last element of V (“10”)
A = ones(10, 20) - create A a 10 ×20 matrix of plot(x, y, ’.g’);
1’s
Common colours:
A(1:3,10:20) = 2 - Changes entries in rows 1-3 r (red), b (blue), k (black), g (green), y (yellow)
and cols 10-20 (inclusive) to value 2.
Changing dot size.
A(end, 1) - Gets last entry in column 1
plot(x, y, ’.’, ’markersize’, 10);
Changing line width.
Reading from Files
plot(x, y, ’linewidth’, 3);
M = csvread(’matrix_filename.csv’); - reads M
Multiple plots on the same axes.
from comma-separated file
plot(x1, y1);
hold on;
Defining Functions
plot(x2, y2);
In a script e.g. f = @(x) x.^2 + 3;
Closing all graph windows.
close all
Powers, Products and Division
In almost every case in the MNTC courses, when
Mathematical Functions
using powers (^), products (*) or division (/)
Trig, with radian values input:
with vectors of values, you want the element by
cos(pi/4), sin(pi/3), tan(pi)
element versions, which had a dot (.) in front of
Trig, with degree values input:
them.
cosd(45), sind(60), tand(180)
Cubing (powers):
Logarithmic:
x = linspace(0, 3);
ln(x) is log(x)
y = x.^3
log10 (x) is log10(x)
Products (e.g. computing cos(x) · x):
Exponential:
x = linspace(0, 3);
ex is exp(x)
y = cos(x).*x
2x is 2^x
ex
Division (computing ):
x
x = linspace(0, 3);
y = exp(x)./x
1
MNTC MATLAB Reference Sheet
Optimization
func - function to be minimized
a, b - interval for searching)
[xopt, fopt] = fminbnd(func, a, b)
To find a maximum, use fminbnd
on -1 × the original function.
Numerical Integration
Left-Hand
Rulen
Z
b
f (x) dx ≈
a
X
f (xi−1 )∆x
i=1
assuming x0 = a
Built-In MATLAB numerical integration
int = integral(func, a, b)
2
Page 2