You are on page 1of 12

MATLAB Workshop

Conducted by Dr. Tan Ai Hui (htai@mmu.edu.my)

A. Introduction to MATLAB
What is MATLAB?
• MATLAB is an abbreviation for Matrix Laboratory, developed by The MathWorks Inc.
• Computing language devoted to processing data in the form of matrices of numbers.
• Integrates computation and visualisation into a flexible computer environment.
• Contains specialized toolboxes. Examples - Communications Toolbox, Control System
Toolbox, Curve Fitting Toolbox, Data Acquisition Toolbox, Fuzzy Logic Toolbox, Neural
Network Toolbox, Signal Processing Toolbox, Simulink, System Identification Toolbox.

Capabilities of MATLAB?
• Numerical computation
• Data access
• Data analysis and visualisation
• Programming and algorithm development
• Application development and deployment

Example of application areas:


• Aerospace and Defense
• Automotive Industries
• Biotech, Medical and Pharmaceutical Industries
• Education
• Communications
• Financial Services

B. Numbers and Variables


Numbers
Standard decimal notation: 2 -89 0.00056
Use e to specify power of ten: 9.6884238 4.60320e-20 7.12252e22
Use i or j to specify imaginary parts in complex numbers: 4i -5.66j 5e7i 2+3j
Floating-point numbers have a finite precision of roughly 16 significant decimal digits.

Special variables and constants


ans - Most recent answer
eps - Floating point relative accuracy
realmax - Largest positive floating point number
realmin - Smallest positive floating point number
pi - 3.1415926535897... (Try format long, format short)
inf - Infinity (Try 1/0)
NaN - Not-a-Number (Try 0/0)

1
Variables
There is no need to declare variable type and dimension prior to usage. MATLAB does automatic
creation of the variable with the correct dimension when the user defines it through an equation.
MATLAB is case-sensitive. (Note that comments are preceded with %.)

A=7; %define variable A


a=2;b=5;c=10; %define variables a, b and c
a=2 %observe the difference when ‘;’ is omitted
d=[1 3 2 7 8]; %define a row vector d
d=[1 3 2 7 8] %observe the difference when ‘;’ is omitted
d(2) %2nd element of d
d(2:4) %2nd to 4th element of d
d=[1;3;2;7;8] %define a column vector d, overwrite previous
e=[1 3;4 5;6 7] %define a 3x2 matrix e
f=[2 3 4;4 4 5] %define a 2x3 matrix f
f(2,3) %row 2, column 3 of f
f(2,:) %row 2, all columns of f
f(:,1) %column 1, all rows of f
size(e) %check matrix size
size(f)
length(e) %give the length of the longer dimension
length(f)
ans %the most recent answer is stored here

Not advisable to use special variables and constants, or existing predefined function names to
represent variables. It will overwrite the variable/constant/function. Examples of predefined
functions: max, var, sin.

d=[1 3 2 7 8];
max(d) %find the maximum value
max=4 %overwrite predefined function. Don’t do this!
max(d) %see now what happens
clear max %clear the variable max
max(d) %now it works again
clear %note that this will clear the whole workspace
max(d) %observe the error message

C. Operators and Basic Functions


Operators
+ - Addition
- - Subtraction
* - Multiplication
/ - Division
\ - Left division (x = A\B is the solution to the equation Ax = B)
^ - Power

2
' - Complex conjugate transpose

d=[1 3 2 7 8];
d=d' %perform transpose of a matrix
e=[2 3 4 7 6]’;
f=[1 2 3 4 5 6];
f=[1:6] %note the use of the ‘:’ sign
g=[1:-0.5:-3]
g(2:3)=[]; %remove 2nd to 3rd elements of g. Size changes
g=d+e %vector/matrix addition. Overwrite previous
h=d+f %matrices of different sizes cannot be added
h=[1 3;2 4] %define a square matrix h
h^2 %perform h times h, similar to h*h
h.^2 %element by element operation
h-1 %subtraction by a constant
sum(f) %sum of a vector
sum(h)
sum(h’) %see how it is different from sum(h)

Exercise 1
A mathematical series has numbers 1, 2, 3, …, 100. Generate the series as a vector. What is the
sum of the numbers in the series?

Answer: 5050

Exercise 2
A mathematical series has numbers 10, 10×0.8, 10×0.82, …, 10×0.816. What is the sum of the
numbers in the series?

Answer: 48.8741

Let’s try more operations with vectors and matrices.

f=[1:6]
h=[1 3;2 4]
g=[1:-0.5:-3]
f*f %incompatible size for multiplication
f.*f %element by element operation
inv(h) %inverse of a matrix
inv(g) %only a square matrix can have an inverse
k=[1 3;2 4];
l=[7;10];
m=k\l %solve m for km=l
det(k) %determinant of a matrix

Try help arith, help relop, help slash.

3
Exercise 3
The variables a, b, c, and d are related to the variables p, q, r and s as follows:

a + 2b + 4c – 5d = p
2a + c – 7d = q
-3a + 5b – c + 10d = r
a+b=s

If p, q, r and s are –5, 2, 3 and 6 respectively, find a, b, c and d.

Answer: a = 4.5045, b = 1.4955, c = -2.2793, d = 0.6757

Functions
Complex numbers
real - Complex real part
imag - Complex imaginary part
abs - Absolute value
angle - Phase angle in radians
conj - Complex conjugate

Try all the above for a=3+4i. Try also to convert the phase in radians to degrees.

Trigonometric
sin - Sine
asin - Inverse sine
cos - Cosine
acos - Inverse cosine
tan - Tangent
atan - Inverse tangent

a=3+4i
sin(angle(a))
asin(sin(0.5)) %returns the same value of 0.5
asin(sin(pi)) %rounding error
cos([1 2 3]) %can work on matrices

Exponential
exp - Exponential
log - Natural logarithm (base e)
log10 - Base 10 logarithm
log2 - Base 2 logarithm
sqrt - Square root

a=[1 2 3;4 5 6]
exp(a)

4
log(a)
log(exp(a))
sqrt(a)

Exercise 4
A bit of memory can store 2 states - 0 and 1 in binary notation. Two bits of memory can store 4
states – 00, 01, 10 and 11, equivalent to numbers 0, 1, 2 and 3. An engineer needs to design a
memory which can store 592048 states. How many bits of memory does he need?

Answer: 20 bits

Exercise 5
Find the decimal equivalent of binary number 110011001100.

Answer: 3276

Miscellaneous functions
who %check the variables in the workspace
whos %display variables in workspace and their sizes
cd %check the current directory
save %save workspace into current directory
%file is in .mat format
clear %clear all the variables
who %
load %load previously saved workspace
who

Try help save to check for more options for saving your variables. Try helpwin for more help
including online help.

D. Plotting of Graphs

plot - Linear plot


semilogx - Semilog for horizontal axis, linear for vertical axis
semilogy - Semilog for vertical axis, linear for horizontal axis
loglog - Log scale for both axes
axis - Define axis
title - Define title
xlabel - Define horizontal axis labelling
ylabel - Define vertical axis labeling
figure - Create a figure window
mesh - 3D mesh surface
contour - Contour plot

d=[1;3;2;7;8]
plot(d) %plot d

5
%vector element number is on the horizontal axis
x=[0:5] %define a vector x
plot(x,d) %not possible to plot 2 vectors of different sizes
x=[0:4]
plot(x,d) %plot d against x
plot(x,d,'k') %change line colour
plot(x,d,'o') %change line type
stem(x,d,'o') %change type of plot to stem plot
stairs(x,d,'o') %change type of plot to stairstep plot
stairs(x,d,'-') %change line type
axis([0 4 0 10]) %specify axis
title('Graph of d against x') %add title
xlabel('x') %add horizontal axis labelling
ylabel('d') %add vertical axis labelling
gtext('I can insert a text anywhere I want')
%place the mouse somewhere in the figure and left click
grid %add grid
grid %remove grid
help plot %’help’ shows you what the function does
%also lists other relevant functions if any
%comes with all built-in MATLAB functions
semilogx(x,d) %plot the horizontal axis using logscale
semilogy(x,d) %plot the vertical axis using logscale
plot(x,x^2) %error due to incompatible dimension
plot(x,x.^2) %plot a quadratic function

Exercise 6
A first order RC circuit is being connected to a voltage supply of 10V. The voltage across the
capacitor is measured at every millisecond starting from time t = 0 (when the voltage supply is
being connected) up to time t = 7ms. The voltages measured (in volts) are 0, 3.2, 5.3, 7.0, 7.8, 8.6,
9.3 and 9.4. Plot the output voltage against time. Label your graph appropriately. Find the time
constant of the first order circuit.

Answer: 2.45ms

What do you do if you need to plot several lines? There are several options. Let’s look at an
example.

x=[0:4]
y=x.^2
subplot(2,1,1) %create 2x1 number of plots in a figure
subplot(2,2,1) %create 2x2 number of plots in a figure
subplot(2,1,1) %specify the 1st plot
%shown by the last number in the bracket
plot(x,y)
subplot(2,1,2) %specify the 2nd plot
%this is the first way to compare 2 plots

6
plot(x,4*x-2)
close %close the plot
plot(x,4*x-2)
figure(2) %open a second plot
%this is the second way to compare 2 plots
plot(x,y)
close
close
plot(x,4*x-2)
hold %hold a plot so that another line can be plotted on it
%typing hold again will release the plot
%hold is an on-off function, just like grid
%this is the third way to compare 2 plots
plot(x,y,'--')

To save a figure file which can be opened by MATLAB, you are recommended to use .fig format.
To export to Microsoft Word, you are recommended to export the figure in .emf format.

E. Signal Processing
Graph fitting and statistical analysis

polyfit - Fit polynomial to data


polyval - Evaluate polynomial
poly - Convert roots to polynomial
roots - Find polynomial roots
mean - Mean
var - Variance
std - Standard deviation
median - Median
max - Maximum
min - Minimum

x=[-3:3]
y=x.^2+x.^3
polyfit(x,y,2) %fitting x and y with a 2nd order polynomial
polyfit(x,y,3) %fitting x and y with a 3rd order polynomial
polyfit(x,y,1) %fitting x and y with a 1st order polynomial
p=polyfit(x,y,1)
p(1) %display 1st element of vector p
p(2) %display 2nd element of vector p
z=polyval(p,x) %evaluate polynomial
plot(x,y) %plot graph between x and y
plot(x,z) %plot the best linear estimate of y
roots(p) %find root(s) of polynomial
difference=y-z %define the error

7
error_squared=difference.^2 %find the error squared
mean(error_squared) %mean
var(error_squared) %variance
std(error_squared) %standard deviation
sum(error_squared) %sum
median(error_squared) %median
max(error_squared) %maximum
min(error_squared) %minimum

Exercise 7
Find the roots of the polynomial y = 3 x10 + 5 x 9 − 7 x 7 − 6 x 5 + 9 x 4 − 10 x 2 + 3 x − 4 . How many real
roots are there?

Answer: 2

Exercise 8
A dependent variable y is known to be related to an independent variable x by a polynomial
relationship. Some measured data are available:

x 0 1 3 5 6 8 10 11
y 2 1 0 -2 1 2 5 6

Fit the data using with the simplest polynomial relationship possible, such that the average of the
error squared is less than 0.5. Using this relationship, find the estimates of y for x = -5, 15 and 25.
Plot the measured data points as circles. On the same graph, plot the estimated relationship between
y and x using a solid line.

Answer: [-0.0072 0.2651 -1.6856 2.2286], mean of error squared = 0.471


Random numbers and probability

rand - Uniformly distributed random numbers


randn - Normally distributed random numbers
hist - Plot histogram

A=rand(2,3) %2x3 matrix of uniformly distributed random numbers


B=rand(1000,1); %uniformly distributed random numbers
C=randn(1000,1); %normally distributed random numbers
subplot(1,2,1)
hist(B) %plot histogram of B
subplot(1,2,2)
hist(C) %observe the difference in the distribution
a=find(C>2) %find indices of elements which are >2
size(a) %check the size of a

8
Exercise 9
Generate a vector r of 10000 random numbers using rand. Find the mean, median, maximum and
minimum of this vector. Verify that the r follows a uniform distribution by checking the probability
of r. For example, you can check the following probabilities: r < 0.1, r < 0.5, r < 0.9, as well as plot
the histogram.

Answer: No standard answer as this involves random numbers.

Fourier transform and inverse Fourier transform

fft - Discrete Fourier transform (DFT)


ifft - Inverse discrete Fourier transform (IDFT)

x=[1 2 -3 -5 4 3 2 3 -4 6 5 3 3]’;
X=fft(x); %convert time signal into frequency domain
%perform DFT
stem([0:12],abs(X)) %plot magnitude of DFT
y=ifft(X); %convert frequency domain back to time domain
%perform IDFT
%not quite the right way to do it
y(1:10) %check to see if it is a real signal
y=real(ifft(X)); %correct way to do it
[x y] %check to see if you get the correct answer
q=[ones(5,1);-ones(5,1)]; %q is a square wave
stem([0:9],abs(fft(q))) %plot the DFT magnitude
q=[ones(50,1);-ones(50,1)]; %q is now sampled 10 times faster
stem([0:99],abs(fft(q))) %observe the improvement

Exercise 10
We know that the Fourier series of a squarewave is given by
1 1
y = sin(t ) + sin(3t ) + sin(5t ) + ...
3 5
Plot the following on the same figure using different line colours:
y1 = sin(t )
1
y2 = sin(t ) + sin(3t )
3
1 1 1 1
y3 = sin(t ) + sin(3t ) + sin(5t ) + sin(7t ) + sin(9t )
3 5 7 9
Using a separate figure, plot the DFT magnitude of y3.

9
F. Loops
If loops
The structure can take various forms as follows. Note that there must be a matching end.

if condition 1 if condition 1 if condition 1


statements 1 statements 1 statements 1
end else elseif condition 2
statements 2 statements 2
end elseif condition 3
statements 3

else
condition n
end

a=1;b=2;
if b>a
display(‘b is greater than a.’)
end

a=1;b=2;
if b>a
display(‘b is greater than a.’)
else
display(‘b is not greater than a.’)
end

a=1;b=2;
if b>a
display(‘b is greater than a.’)
elseif b==1
display(‘b is equal to a.’)
else
display(‘b is smaller than a.’)
end

For loops
The structure is as follows:

for variable = start_value:increment:end_value


statements
end

%loops
for x=1:10 %define a for loop starting from x=1 to x=10
%increment=1

10
z(x)=x^3
end

Let’s try another example, now for a filtering type of operation. Let’s say y (t ) = x(t ) − y (t − 1) .
Given that x(1)=1, x(2)=3, x(3)=4, x(4)=6, x(5)=7, x(6)=8, find y(t), with y(0)=0.

x=[1;3;4;6;7;8];
y(1)=x(1) ;
for t=2:6
y(t)=x(t)-y(t-1)
end

Exercise 11
Two variables x and y form two time series. Variable y is dependent on x as follows:

y (t ) = x(t ) − [ x(t ) − y (t − 1)] exp(−0.2t )

It is given that x = 1, 0, 2, 3, -1, 0, 3, -2 during the time from t = 1 to 8 seconds. Find y assuming
that x and y are both zero for t = 0. Plot x and y on the same graph using different line styles.

Answer: y = [0 0.1813 0.1215 0.9691 2.0874 0.1358 0.0409 2.2703 -1.1378]

Nested loops
There are an infinite number of possibilities. Some examples are given below:

if condition 1
statements 1
for variable = start_value:increment:end_value
statements 2
end
end

for variable = start_value:increment:end_value


statements 1
if condition 1
statements 2
else
statements 3
end
statements 4
end

x=[1:10];
for t=1:length(x)
if x(t)>4
disp('Yes')
else

11
disp('No')
end
end

The ‘display’ command is a helpful tool for debugging. When you have a large number of loops,
you can pinpoint the location of an error if you use several ‘display’ commands to display certain
text. It allows you to see which path the program runs through when you have if and else
statements.

Exercise 12
Write some codes to check if the number 15 is a prime number. (Of course we know it is not, but
we do this for the sake of programming exercise.) Hint: Use the structure below:
set a variable to indicate whether it is prime. Let’s call the variable is_it_prime.
set is_it_prime to 1 by default (1 means prime, programmer must define this)
for 2 to 14
try to divide 15 by the number and check if the remainder is 0 (use rem function)
if the remainder is 0
we know it is not a prime number, so set is_it_prime to 0
end
end
now check whether is_it_prime is 1 or 0

12

You might also like