Vous êtes sur la page 1sur 10

AN INTRODUCTION TO MATLAB

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

4 Suppressing the Output


If the symbol ";" is placed in front of an expression, the value of the variable is calculated but is not shown on the
screen. Try this:
>>x=5; y=x*2, z=y+1
y= 10
z= 11
Note: - z exists only as a numerical value, not as the formula.
- the value of x is not shown.

ƒ 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;

6.1 Row vectors:


- List of numbers separated by either space or commas,
- The number of entries is known as "length",
- The entries are referred to as "elements" of the vector.
To create a row vector of length 5, filled with ones use
>> x = ones(1,5)

>> 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

>> v = [2*z, -w], sort(v)


v = 18 20 -2 -4 -7

ans = -7 -4 -2 18 20 Note: v is sorted into descending order by the command sort(v)

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.

6.3 Addressing vector elements


ƒ Individual elements of a vector can be addressed as follow:
>> x = linspace(11,15,5);
>> x(2)

ans = 12

MATLAB automatically interprets the index as the appropriate row or column

ƒ Increasing the size of a vector (or scalar)


Matlab allows you to increase the size of a vector simply by assigning a value to an element that has not been
previously used. Examples
>> x = [-1.3 sqrt(3) (1+2+3)*4/5],

x = -1.3000 1.7321 4.8000

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

ƒ Block of elements at a time: Matlab uses colon notation:


>> r = [1:2:10, -2:-2:-9]
r = 1 3 5 7 9 -2 -4 -6 -8
>>
We are interested in the 3rd and 6th elements:
>> r(3:6)
ans = 5 7 9 -2

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)

Here elements are separated by ";" or "new lines"

>> a = [1; 2; 5; sqrt(6)]


a = 1.0000
2.0000
5.0000
2.4495
>>

>> a2= [3
4
5
9]

a2 =
3
4
5
9

>> a3 = 2*a - 3*a2

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

t = 5.0000 10.0000 21.0000 14.3485


6.6 Arithmetic on Vectors: Vectors may be operated by the standard operators +, -, * and ÷.
6.6.1 Addition and Subtraction

>> a=[2 3 4 5 6], b=[1 0 -3 4 7], d=a+b, e=a-b


a= 2 3 4 5 6
b = 1 0 -3 4 7
d = 3 3 1 9 13
e = 1 3 7 1 -1

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

6.6.4 Arithmetic on Arrays


The term array operation refers to element -by-element arithmetic operations, instead of the usual linear algebraic
matrix operation.
A period (.) preceding an operator indicates an array or element-by-element operation.

ƒ Addition and Subtraction: Are the same as the matrix operation.


ƒ Multiplication and Division: The symbol .* denotes array, or element-by element, multiplication.
If A and B have the same dimension, then A.*B denotes the array whose array are simply the product of individual
elements of A and B For example:
>> A = [1 2 3], B=[4 5 6], z= A.*B
A= 1 2 3

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.1 Addressing matrix elements


Matrix elements are referred to with the subscript notation. If A is a matrix, then A(2,3) is the element in the second row
and third column.
Example: 3x3 matrix
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> A(2,3) % ask MATLAB to print the (2,3) element
ans = 6
>> A(3,2) = -5 % reassign the (2,3) element
A =
1 2 3
4 5 6

7.2 The ones function


Creates a matrix whose elements are all ones. Typing ones(m,n) creates an m row by n column matrix of ones. To
create a ones matrix that is the same size as an existing matric, you can use ones(size(X)). This does not affect the input
argument.
For example:
>> x = [1 2 3 4; 0 9 3 8]
x =
1 2 3 4
0 9 3 8
>> y = ones(size(x))
y =
1 1 1 1
1 1 1 1

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

7.5 sum and prod functions


If z is a vector, sum(z) is the sum of all the elements of the vector z:
>> sum(z)
ans = -11
Similarly, prod(z) is the product of all the elements of z.
>> prod(z)
ans = -810

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.

10 Editor and M-Files


These are the program files in MATLAB used to develop meaningful programs which encompasses all the necessary
code for a particular application.

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.

11.2 Help Facility


A HELP facility provides online information for most Matlab topics. The command
>> help
with no arguments displays a list of directories that contains Matlab related files.

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.

11.3 Saving the Workspace


ƒ File Saving: You can save the workspace by typing "save". In the NOTEPAD Editor there is a save command
which can be used to save files. The save command saves all variables in a file on disk named matlab.mat.
ƒ Save Temp: You can save only selected variable. The command save temp stores the current variables in the file
name tem.mat. For example:

save temp x
saves only variable x, while
save temp x y z
saves x, y and z.

11.4 Control Structures (Loop and Conditional Statements)


11.4.1 The "For" commands: This allows a command or series of commands to be executed several times. Similar
to the for function in C. Caution: Do not to use the variable i for an index; else, you may inadvertantly redefine
sqrt(-1). For example, typing
for x = 1:5
x
end
The Matlab would return:
x= 1
x= 2
x= 3
x= 4
x= 5
Nested for loops: Every for command must have a matching end statement.
Example:
for m = 1:3
for n = 1:3
x (m,n) = m + n*i;
end
end

Matlab defines x to be the matrix:


x=
1.0000 + 1.0000i 1.0000 + 2.0000i 1.0000 + 3.0000i
2.0000 + 1.0000i 2.0000 + 2.0000i 2.0000 + 3.0000i
3.0000 + 1.0000i 3.0000 + 2.0000i 3.0000 + 3.0000i

11.4.2 The "If" command


Allows you to have programs that make decisions about what commands to execute.
Example:
if a > 0
x = a^2;
end

This command assigns x to be the value of "a" squared, if a is positive.


Note: It must end with end to indicate which commands are actually part of the if.

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.

11.4.3 The "while" command


It allows execution of a group of commands until some condition is no longer true. These commands appear between
the while and its matching end statement.

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.

11.4.4 The "pause" and "keyboard" commands


ƒ The pause command causes MATLAB to wait for a key to be pressed before continuing.
ƒ The keyboard command passes control to the keyboard, indicated by the prompt K>>. You can examine or change
variables, or issue any MATLAB command. Terminate keyboard mode by executing the command return at the
K>> prompt.
The break command be used to jump out of a for or while command earlier than expected.

Example: Rewrite the while example as:


while 1
if x > 1000000
break;
end
x = x^2;
end

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

Vous aimerez peut-être aussi