www.tlc.polito.it

Download Report

Transcript www.tlc.polito.it

Master in Optical Fiber Communications and Photonic Technologies
Introduction to
Matlab
Foundations of Digital Transmission - Fall quarter
What Is MATLAB?
MATLAB is an interactive program for scientific and
engineering numeric calculation.
It integrates computation, visualization, and
programming in an easy-to-use environment where
problems and solutions are expressed in familiar
mathematical notation.
Typical uses include:
Math and computation
Algorithm development
Modeling, simulation, and prototyping
Scientific and engineering graphics
Copyright 2001 OCG
2
Command Window
Command Window is used to enter variables and run
functions and M-files.
Navigation within MATLAB is done using regular UNIX
commands
cd (change directory)
pwd (show the path)
ls (list contents of directory)
whos (list of the variable stored in the memory)
In latest version, most of this is also available using a
graphical interface
Copyright 2001 OCG
3
Command Window
Getting help from the command window
help <function_name> (show the help document for a given function)
By the way you can use this help only if you know the name of the function
to be used. If you do not know it, just use the windows help, which is
much more easy and complete. Here you can find also several examples.
P.S.
If you want to have an help for your own functions, you can write it at the
beginning of the function as :
% your own help.
After this statement, the matlab file will start.
Copyright 2001 OCG
4
Variables
MATLAB does not require any type declarations!
Real scalar:
Complex scalar:
Row vector:
Column vector:
2x2 Matrix:
>>
>>
>>
>>
>>
x=1
x=1+2i
x=[1 2 3]
x=[1; 2; 3]
x=[1 2; 3 4]
You can define global variables by putting in front the
variable the statement global.
Copyright 2001 OCG
5
Complex numbers
Some useful operations on complex numbers:
Complex scalar
Real part of x
Imaginary part of x
Magnitude of x
Angle of x
Complex conjugate of x
>>
>>
>>
>>
>>
>>
x = 3+4j
real(x)
imag(x)
abs(x)
angle(x)
conj(x)
Copyright 2001 OCG
->3
->4
->5
->0.9273
->3 - 4i
6
Generating vectors
>> x=[a:step:b]
Generate a vector that takes on the values a to b in
increments of step
>> x=linspace(a,b,n)
generates a row vector x of n points linearly spaced
between a and b
>> x=logspace(a,b,20)
generates a logarithmically spaced vector x of n points
between 10^a and 10^b.
Copyright 2001 OCG
7
Generating matrices
Matrix building functions:
>> A=zeros(m,n)
returns an m-by-n matrix of zeros
>> A=ones(m,n)
 returns an m-by-n matrix of 1s
>> A=eye(m,n)
 returns an m-by-n matrix with 1's on the diagonal and 0's
elsewhere
Copyright 2001 OCG
8
Generating random matrices
>> A=rand(m,n)
 returns an m-by-n matrix of random numbers whose elements are
uniformly distributed in the interval (0,1)
>> A=randn(m,n)
 returns an m-by-n matrix of random numbers whose elements are
normally distributed with mean 0 and variance 1
>> A=randint(m,n,range)
 generates an m-by-n integer matrix. The entries are uniformly
distributed and independently chosen from the range:
[0, range-1] if range is a positive integer
[range+1, 0] if range is a negative integer
Copyright 2001 OCG
9
Accessing matrix elements
Elements of a matrix are accessed by specifying the
row and column
>> A=[1 2 3; 4 5 6; 7 8 9];
>> x=A(1,3)
Returns the element in the first row and third column
>> y=A(2,:)
Returns the entire second row [4 5 6]
“:” means “take all the entries in the column”
>> B=A(1:2,1:3)
Returns a submatrix of A consisting of rows 1 and 2 and
all three columns [1 2 3; 4 5 6]
Copyright 2001 OCG
10
Arithmetic matrix operation
The basic arithmetic operations on matrices are:
+ addition
- subtraction
* multiplication
/ division
^ power
’ conjugate transpose
MATRIX-wise operation
This operation are to be meant in the “matrix sense”
Copyright 2001 OCG
11
element-by-element operations
MATLAB provides element-by-element operations by
prepending a ‘.’ before the operator
.* multiplication
element-wise operation
./ division
.^ power
.’ transpose (unconjugated)
BE CAREFUL when operating on matrix: the meaning of
the two operations .* and * are completely different
Copyright 2001 OCG
12
Relational operations
MATLAB defines the following relational operations:
<
<=
>
>=
==
~=
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to
Copyright 2001 OCG
13
Logical operations
MATLAB defines the following logical operations:
& and
| or
~ not
Copyright 2001 OCG
14
Math functions
The following functions operate element-wise, also
when applied to a matrix:
sin
asin
sinh
exp
abs
cos
acos
cosh
log(natural log)
sqrt
Copyright 2001 OCG
tan
atan
tanh
log10
sign
15
M-files
MATLAB is an interpretive language
M-files are text files containing MATLAB scripts
Scripts are sequences of commands typed by an editor
The instructions are executed by typing the file name
in the command window at the MATLAB prompt
All the variables used in the m-file are placed in
MATLAB’s workspace that contains all the variables
defined in the MATLAB session
Copyright 2001 OCG
16
M-files Debug
In Matlab you can debug your m-file, like in other
programming languages
To do it, you need to open your matlab file from the
window command.
Afterwards, you can operate exactly like for other
languages and you can use usual command as:
step in
step out
break point
etc. etc
Copyright 2001 OCG
17
Flow control
If statements
Example
if expression
statements
else
statements
end
If n<0
a=a-1;
else
a=a+1;
end
Copyright 2001 OCG
18
Flow control
For
Repeats a group of statements a fixed, predetermined
number of times.
a=0;
for n = 1:10
a=a+1;
end
Copyright 2001 OCG
19
Function in Matlab
To simplify your matlab file structure, you can use
functions. An example of how to use Matlab functions is
the following:
Main Matlab Program
SegEqRx = SegEqNew + 1*SegRx(DimC*TTaps+1:LRx-DimC*TTaps);
clear SegEqNew; clear SegEqOld;
[SAMPLE_CENTRAL, BIT_DETECTED] =
=syncronizer(SegEqRx,PNSEQ_VECTOR,NS_BIT,NBIT_PNSEQ);
…
Function declaration:
function [ SAMPLE_CENTRAL, BIT_DETECTED]
=syncro(SIGNAL,PNSEQ_VECTOR,NS_BIT,NBIT_PNSEQ);
Main of the function
Copyright 2001 OCG
20
Creating a plot
>> plot(x,y)
produces a graph of y versus x, where x and y are two
vectors
1
0.8
x=linspace(0,2*pi,100);
plot(x,sin(x));
0.6
0.4
Sine of x
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
x
Copyright 2001 OCG
21
Line styles and colors
It is possible to specify color, line styles, and markers
when you plot your data using the plot command
plot(x,y,'color_style_marker')
color_style_marker is a string containing from one to
four characters constructed from a color, a line style,
and a marker type:
Color strings: 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These
correspond to cyan, magenta, yellow, red, green, blue,
white, and black
Linestyle strings are '-' for solid, '--' for dashed, ':' for
dotted, '-.' for dash-dot, and 'none' for no line
The marker types are '+', 'o', '*' and 'x'
Copyright 2001 OCG
22
Axis lables and titles
xlabel('string')
labels the x-axis of the current axes
ylabel('string')
labels the y-axis of the current axes
Title(‘string’)
add a title to a graph at the MATLAB command prompt or
from an M-file
Copyright 2001 OCG
23
The figure function
MATLAB directs graphics output to a figure window
Graphics functions automatically create new figure
windows if none currently exist
>>figure
creates a new window and makes it the current figure
>>figure(h)
make an existing figure current by passing its handle (the
number indicated in the window title bar), as an
argument to figure
>>clf
Clear current figure window
Copyright 2001 OCG
24
Adding plots
Setting hold to on, MATLAB doesn’t remove the existing
graph and adds the new data to the current graph
0.8
0.6
0.4
0.2
Sine of x
x=linspace(0,2*pi,100);
plot(x,sin(x));
hold on;
plot(x,cos(x));
xlabel('x');
ylabel('Sine of x');
1
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
x
Copyright 2001 OCG
25
Adding plots
With more graphics
functionalities:
x=linspace(0,2*pi,100);
plot(x,sin(x),’-ob’);
hold on; grid on;
plot(x,cos(x),’->r’);
xlabel('x');
ylabel('Sine of x');
legend('sin(x)','cos(x)',3)
Copyright 2001 OCG
26
Basic plotting commands
Plot
Graph 2-D data with linear scales for both axes
Loglog
Graph with logarithmic scales for both axes
Semilogx
Graph with a logarithmic scale for the x-axis and a linear
scale for the y-axis
Semilogy
Graph with a logarithmic scale for the y-axis and a linear
scale for the x-axis
Copyright 2001 OCG
27
Specialized plots
bar(x,Y)
draws a bar for each element in Y at locations specified
in x, where x is a monotonically increasing vector
defining the x-axis intervals for the vertical bars
>> bar((1:1:10),(1:1:10))
Copyright 2001 OCG
28
Specialized plots
Stem
displays data as lines (stems) terminated with a marker
symbol at each data value
x=linspace(0,2*pi,10);
stem(x,sin(x));
Copyright 2001 OCG
29
Specialized plots
Stairs
Stairstep plots are useful for drawing time-history plots
of digitally sampled data systems
x=linspace(0,2*pi,20);
stairs(x,sin(x));
Copyright 2001 OCG
30