Académique Documents
Professionnel Documents
Culture Documents
1 Introduction
MATLAB is a powerful mathematical tool used for a number of engineering applications such as communication
engineering, digital signal processing, control engineering, artificial intelligence, etc. .
1.1 Workspace
On Windows systems Matlab is started by double clicking on the Matlan icon. On opening MATLAB the Command
Window is created and made the active window. The Command Window is the mechanism through which one can
communicate with the Matlab interpreter. The interpreter displays it prompt ">>" on the right hand side of the screen,
indicating that it is ready to accept instruction. If after entering instructions Matlab Command Window display no ">>"
then is means that Matlab is still executing the commands. Once finished the symbol ">>" will be displayed.
Type 1 at the command line and press return. The program immediately replies with
ans = 1
What has happened is that a variable has been created called ans and the value 1 placed in it.
Repeat the procedure with the number 2.
Many functions are built into MATLAB from the basic package through to the use of numerous toolboxes specific to a
particular application.
Typing help lists the top level for the help contents available.
MATLAB also provides the user with the common looping and selection statements for building specific programs.
2 Matlab as a Calculator
All the basic arithmetic operators +. -. *, / and ^ are used together with ( ). ^ is used to show the power: 2^3 = 8.
Type in the followings:
>> 3 + 4/6*9
ans = 9
Note: Matlab works according to the priorities as:
1- Quantities in brackets
2- Powers
3- * and / , working left to right
4- + and -, working left to right.
3 Variables
3.1 Scalars: A scalar is a simple variable with one column and one row.
3.3.1 Creating scalars: To create a scalar assign a value to a name. Try the following and verify z.
>> x = 1;
>> y = 2;
>> z = x + y;
3.3.2 Scalar operations: MATLAB supports the standard scalar operations using an obvious notation. The following
statements demonstrate scalar addition, subtraction, multiplication and division.
>> u = 5;
>> v = 3;
>> w = u + v
>> x = u - v
>> y = u * v
>> z = u/v
You may use the "who" command to list all the currently active variables.
>> who
Your variables are:
ans x y z
leaving 7433616 bytes of memory free.
Exercise 4.1: in each case find the value of the expression and explain the order in which the calculation is carried
out.
i) -3^4+9
ii) 4*5/6
iii) 2*9-5^4-3
iv) (2/4^2+7)*(5-3^2)^4
5 Built-In Functions
5.1 Trigonometric functions: sin, cos, tan
Example 5.1: Work out the co-ordinates of a point on a circle of radius 7 centred at the origin with an elevation of
45o (i.e. π/4 radians):
>> x = 7* cos (pi/4), y = 7 * sin (pi/4)
x = 4.9497
y = 4.9497
5.2 Other functions: sqrt (for √), exp (for exponential e2), log, log10 (for log10 ) etc.
Exercise 5.1: For x = 9 find sqrt (x), exp (x), log 9x), and log10 (x).
6 Vectors
Most calculations in Matlab are vector or matrix manipulations. Vectors (and arrays) are accomplished by using the
colon separator, which generates a count of values from a start value to a finish value with a particular increment. The
easiest way to enter small matrices is to enter explicit list following these conventions:
Separate the explicit list elements with blank or commas.
Surround the elements with [ ].
Use ; (the semicolon) to indicate the ends of row.
The linspace and logspace functions create vectors (row and/or columns) with linearly spaced or
logarithmically spaced elements, respectively.
Examples:
>> x = linspace(1,5,5)
x = 1 2 3 4 5
>> y = logspace(1,4,4)
y = 10 100 1000 10000
Assigning vector expressions to a vector
Having created a vector, it can be assigned to another vector.
>> x = zeros(1,5);
>> y = x;
>> b = [1 2, 5 sqrt(6)]
b = 1.0000 2.0000 5.0000 2.4495
>>
Note: b is a vector of 4 elements (one row plus 4 columns).
>> length(b)
ans = 4
Exercise 6.1: Try out the following and notice the difference that spaces can make:
(i) b2 = [2+ 5 4 6] (ii) >> b3 = [2 +5 4 6]
Arithmetic operation with vector: This can be done provided the vectors have the same length, see below:
>> b + b3
ans = 3.0000 7.0000 9.0000 8.4495
>> b4=4*b
b4 = 4.0000 8.0000 20.0000 9.7980
>> b5 =2*b -4*b3
b5 = -6.0000 -16.0000 -6.0000 -19.1010
>>
How about b6 = b + b2?
>> b6=b + b2
??? Error using ==> + Note: The error is because b and b2 do not have the
Matrix dimensions must agree. same
Vectors can be multiplied by a number (a scalar),
or it can be added/subtracted to another vector of the SAME LENGTH. The operation are carried out element -by-
element.
>> w = [ 2 4 7], z = [9 10]
w= 2 4 7
z = 9 10
6.2 The colon notation: A short cut producing a long vector, as:
>> 1:10
ans = 1 2 3 4 5 6 7 8 9 10
>>
How about vector a = 1:-1?
Try this:
>> v = [0:10:100]
ans v = 0 10 20 30 40 50 60 70 80 90 100
It creates a regularly spaced vector (v) containing 11 elements from 0 to 100 at increment of 10.
ans = 12
x(5) = abs (x(1)) Assigns the absolute (abs)value of element 1 to the element (column) five.
x = -1.3000 1.7321 4.8000 0 1.3000
>>
Notice that the size of x is automatically increased to accommodate the new element (element 5) and that the undefined
intervening elements are set to zero.
>> x = linspace(21,25,5)
x = 21 22 23 24 25
>> x(7) = -9
x = 21 22 23 24 25 0 -9
6.4 Column Vector: Have similar construct to row vector. To create a column vector of length 5, filled with zeros
use
>> y = zeros(5,1)
>> a2= [3
4
5
9]
a2 =
3
4
5
9
a3 =
-7.0000
-8.0000
-5.0000
-22.1010
6.5 Transposing Vectors: A row vector can be converted into a column vector (and vice versa) by transposing
the vectors, as shown:
>> w, w'
w= 2 4 7
ans =
2
4
7
>> a, a'
a=
1.0000
2.0000
5.0000
2.4495
ans = 1.0000 2.0000 5.0000 2.4495
>>
>> q = [2 4 6 7], t = q + 3*a'
q= 2 4 6 7
6.6.2 Multiplication: The symbol * denotes multiplication of matrices. The operation is defined whenever the inner
dimensions of the two operands are the same. Note we can not multiply the vector a by vector b directly. This is
because they both have the same dimension of (5,1). For the multiplication to be possible the dimension of vector b
need to change to (1,5). We can do this by transposing the vector b by using the symbol " ' ".
>>f=a*b'
6.6.3 Division:
>> g=a/b
B= 4 5 6
z= 4 10 18
Or
Z = A./B
Results in
Z = 0.2500 0.4000 0.5000
7 Matrix
Example: 2 x 2 matrix A
>> A = [1 2; 3 4]
A =
1 2
3 4
7.3 The zeros function: Typing zeros(m,n) creates an m-by-n matrix of zeros, and zeros(size(x)) will create a two-by-
four matrix of zeros, if x is defined the same way as above.
7.4 The max and min functions: Return the largest and smallest values in a vector. For example (this definition of z
applies to the following series of examples):
>> z = [1 2 -9 3 -3 -5]
z = 1 2 -9 3 -3 -5
>> max(z)
ans = 3
8 Complex Numbers
In Matlab complex number is indicated by the special function "i" and "j". For example
z = 3 + 4i
or
z = 3 + 4j
>> x = [4+5i 2 4; 1 3+i 7]
x=
4.0000 + 5.0000i 2.0000 4.0000
1.0000 3.0000 + 1.0000i 7.0000
9 Creating Strings
Matrices with character elements are known as strings, where the normal rules of assignment and variable creation
apply.
Example: how to create string variables.
>> first = 'John';
>> last = 'Coltrane';
>> name = [first,' ',last]
The first two lines define two string variables, whereas the last line creates a new string variable from three other
strings.
Up to now you were using the Matlab in its real time operation mode. That is as you entered the commands, they were
executed immediately and you could observe the results. In this mode if you leave the Matlab you will loose all your
instructions.
If the process requires many different operations, they are typed in a file using an Editor. Then the file can be saved
and modified as required. The matlab files all have the extension .m. For example: miniproject.m.
A simple editor is NOTEPAD editor. To use it, from Matlab screen, Click on File, then NEW, and then select M-FILE.
A blank file will appear in front of you. Try the following and verify z.
x=5;
y=2
z=x*y
Save the file as temp.m. Exit the NOTEPAd Editor to go back to Matlab Command Window. Type in:
>> temp {followed by return}
This will execute the instruction in the file temp.m. If the operation is successful you should see the value of z=10,
printed on the screen. Of course you could go back and modify your file, save and then execute the file again.
11 In-built Functions
MATLAB has many library functions e.g. sin, tan, cos. These functions take, in addition to scalar parameters, vectors
and matrices as well. For more information see the attached document on Matlab.
11.1 Plotting
Plotting is a simple task using the plot function plot() and will automatically plot the elements of a vector e.g. plot(v) by
default the independent axis uses the vector index number.
For a list of functions covered by a particular directory, type help followed by the directory name or followed by a
function name. For example:
>> help filter
List all the matrix functions relevant to generating digital filter.
>> help plot
Describes how plotting is done in Matlab.
save temp x
saves only variable x, while
save temp x y z
saves x, y and z.
In addition, one can define an else clause, which is executed if the condition given for the if is not true.
Example:
if a > 0
x = a^2;
else
x = - a^2;
end
For this version, if you had already set a to be 2, then x would get the value 4, but if a was -3, x would be -9.
Note: only one end (after all the clauses of the if) is required.
The if can be expanded to include several possible conditions. If the first condition isn't satisfied, it looks for the next,
and so on, until it either finds an else, or finds the end.
Example:
if a > 0
x = a^2;
elseif a == 0,
x = i;
else
x = - a^2;
end
Here a is checked to see if it is positive: if not, it is then checks to see whether it is zero; if a is not zero, it does the else
clause. Thus, if a is positive, x well be a squared, if a is 0, x will be i, and if a is negative, then x will be the negative of
a squared.
Example: We want to start x at 2 and keep squaring it until it is greater than one million.
x = 2
while x < 1000000
x = x^2;
end
It runs until x is 4.2950e+09. Everything between the while line and the end is executed until the boolean condition on
the while line is no longer true. One needs to ensure that this condition will eventually stop being true, or the command
will never finish. If it is not initially true, no commands will be executed.
12 Logical Functions
True or false in Matlab are presented as:
True = 1, false = 0.
The following logical tests may be taken on a particular variable, function etc.:
x == 2 is x equal to 2?
x ~= 2 is x not equal to 2?
x > 2 is x greater than 2?
x < 2 is x less than 2?
x >= 2 is x greater than or equal to 2?
x <= 2 is x less than or equal to 2?
>> x=pi
x = 3.1416
>> x~=3, x~=pi
ans = 1
ans = 0
>>
12.1 Masking out
t = 0:0.05:6;
v = sin(pi*t);
x = (v >=0)
w= x.*v;
plot(t,v, '+', t,w,'*');
Tutorials
For the following tutorial you may use the NOTEPAD Editor. You need to save the file in Matlab directory.
Example 1 Plot two cycles of a sin wave at a frequency of 1 kHz, for the following resolutions
(a) 100 points / cycle, (b) 50 points/ cycle, and (c) 10 points / cycle
Solution: Type in the following Matlab codes and save it (with a name such as " example1.m ") to your own Matlab
work directory.
% Name:
% Date:
% Filename: example1.m
clear % free/clear memory
close all % close all the previous graphs
% Variables initialisation
f=1000; % 1 kHz frequency
res=100; % resolution of 100 points
tc=1/f; % time for one cycle of sine wave
nc=2; % Number of cycles to plot
dt=tc/res; % Step size, also known as the sampling frequency /Variables initialisation
t=0:dt:nc*tc; % time vector start from 0 and step up by step-size "dt" to tc
(2 cycles).
y=sin(2*pi*f*t); % sine wave for 2 cycles. The amplitude by default is 1,
unless is multiply by a magnitude
plot(t,y) % plot 2 cycles of "sine-wave" against the time "t"
title ('1 kHz sinewave')
xlabel('time (s)'), % labelling the time (or x-axis)
ylabel('amplitude (v)') % labelling the time (or y-axis)
Example 2 Add further codes to the example 1 and save the file as example2.m. Plot sine wave against time,
radian and degree
Solution:
% Filename: example2.m
% Variables initialisation
w=2*pi*f; % radian per second
dg=0:360/res:nc*360; % x-axis in degree
ra=t*w; % x-axis in radian
y=sin(w*t); % sine wave for 2 cycles. The amplitude by default is set to 1.
subplot(3,1,1), % breaks the Figure window into an m-by-n matrix of small axes. For more information use
the help command (help subplot)
plot(t,y) % plot the 2 cycles sine_wave against time
xlabel('time (S)'),
ylabel('amplitude (V)')
subplot(3,1,2),
plot(ra,y) % plot the 2 cycles sine
wave against radian
legend ('1 kHz sinewave') % Puts a legend on the
figure
xlabel('radian'),
ylabel('amplitude (V)')
axis([0 4*pi -1 1])
subplot(3,1,3),
plot(dg,y) % plot the 2 cycles
sine_wave against degree
xlabel('degree (o)'),
ylabel('amplitude (V)'),
axis([0 nc*360 -1 1])
Example 3 Add further codes to the end of example2.m file and save it as example3.m. Plot sine wave from 90 degree
to 450 degree,.
Solution:
figure % opens a new graph
start_point=find(dg==90); %look for the index where the 90 is located in the matrix/vector degree
stop_point=find(dg==450); %look for the index where the 450 is located in the matrix/vector degree
plot(dg(start_point:stop_point),y(start_point:stop_point))
axis([90 450 -1 1])
Example 4: Using loops
Draw graphs of sin (nπt) on the interval -1< t < 1, for n = 1, 2, …8.
Solution:
t = -1: 0.05: 1;
for n = 1: 8
subplot (4, 2,n)
plot (t, sin(n*pi*t))
end
Professor Z Ghassemlooy
May 2003