Professional Documents
Culture Documents
of
In this lab we would have a review of MATLAB and get started with working in its
wonderfully simple environment.
MATLAB,
which
stands
for
Matrix
Laboratory,
is a very powerful program for performing numerical and
symbolic calculations, and is widely used in science and engineering, as well as
in mathematics.
Prela
b
1. You are basically responsible for learning MATLAB language on your
own. So read this
Experiment carefully and try to do an example of your own for each
part on MATLAB.
2.
3.
4.
From this moment, any file you will be asked to do in this course will
be saved in these folders.
Lab
What is
MATLAB?
A high-performance language for technical computing. Typical uses of MATLAB:
Mathematical computations.
Algorithmic development.
DSP LABORATORY:
EXPERIMENT#1
Basics of MATLAB
DSP LABORATORY:
EXPERIMENT#1
Command
Window
Curre
nt
Workspace
Folde
r
Command
History
Command Window
-
Figure Window
-
Workspace Window
-
Getting Started
*
/
.*
^
.
:^
(
[) ]
.
,
;
=
%
Operation
Plus; addition operator.
Minus; subtraction operator.
Scalar and matrix multiplication operator.
division operator
Array multiplication operator.
Scalar and matrix exponentiation operator.
Array exponentiation operator.
Colon; generates regularly spaced elements and represents an entire
row
or column.
Parentheses;
encloses function arguments and array indices;
overrides enclosures
precedence.
Brackets;
array elements.
Decimal point.
Ellipsis; line-continuation operator.
Comma; separates statements and elements in a row.
Semicolon; separates columns and suppresses display.
Assignment (replacement) operator.
Comment operator: inserts comments in the program
General Commands
help
topic provides help on topic
who
list variables currently in the workspace
whos
lists variables currently in the workspace
with their size. what
lists m-, mat-, and mex.
files on the disk.
clear
clears the workspace, all
variables are removed clear x,y,z
clears only
variables x, y and z
clear all
clears all variables and functions from workspace
clc
clears command window, command
history is lost. clf
clears figure window
cd
change the current
working directory dir
list
contents of the current directory mkdir
creates a directory
Variables
price_mango = 15
creates a 1 - by - 1 matrix named price_mango and stores the value
15 in its single
element.
Numbers
All numbers are stored internally using the long format specified by
the IEEE floating
point standard. Floating point numbers have a finite precision
of roughly 16 significant decimal digits and a finite range of roughly
-308
+308
10
to 10
3,
99,
0.0001,
9.6412,
1.2 10,
6.2 11,
1,
3.15,
65
Display Formats
Display of numeric value of using different formats
MATLAB
Commands
format short
format long
format short e
format long e
format hex
format bank
format +
format rat
Displayed value of
3.1416
3.141592653589793
3.1416e+000
3.141592653589793
e+000
400921fb54442d18
3.14
+
355/113
Comments
Default display in five digits
Maximum 16 digits can be
displayed
5 digit plus exponent
16 digit plus exponent
Hexadecimal
2 decimal places
Positive only, negative 0
Ratio of whole numbers
(fraction)
_ underscore
Donts
Keywords of MATLAB e.g. sum , randn, end, etc.
Special characters e.g. @, $, !, ., ( ) etc.
Start with numerals e.g. 2_ab is illegal file name
Space between letters/numerals e.g. a 2b is
illegal file name
0
1
-3
3
>>
2:5
ans
=
2
3
5
Typing j:i:k defines a row vector with increment i starting at j and ending at k.
>>
3:2:9
ans =
3
5
ans
=
5 1
-2 17
9 8
It is also possible to view multiple entries within any row or column. For
instance, the second and fourth entries in the third row are accessed as
follows.
>>
A(3,:)
ans =
10 15
>>
A(:,3)
ans =
7
2
-2
-2
M=
nxm matrix of
ones:
M=
zeros(n,m);
ones(n,m);
nxn identity
matrix:
M = eye(n);
M=randn(n,m);
But there is a better way. The colon by itself refers to all the elements in a row or
column of a matrix and the keyword end refers to the last row or column. So
sum(A(:,end)) %computes the sum of the elements in the last column of A.
Dimension Functions
Dimensioning is automatic in MATLAB. You can find the dimensions of an existing
matrix with the
size. Also the command length(x) returns the length of the vector x
>> X=[1 2 3;6 7 8]
>> [m,n] = size(X)
>> x = ones(1,8);
>> n = length(x)
Concatenat
ion:
Concatenation is the process of joining small matrices to make bigger
ones. In fact, you made your first matrix by concatenating its individual
elements. The pair of square brackets, [ ], is the concatenation operator. To do
so horizontally, we separate the arrays with spaces or commas:
>> [ones(2,3), zeros(2,3)]
To do so vertically, we separate the arrays with a semicolon:
>> [ones(2,3); zeros(2,3)]
complex(x,y)
real(x)
imag(x)
abs(x)
angle(x)
conj(x)
cart2pol
pol2cart
and
or
not
If the increment inc is not specified, a default value of 1 is used. For example
x=[ ];
for i=1:4
x=[x,i^2]
end
x=
1
x=
1
4x=
4
1
x=
4
1
9
9 16
Branching if Loop
if relation
true alternative
els
false alternative
e
en
d
if
1>
2
a=
1
else
a=
2
en
da
=
2
Graphics in
MATALB:
Creating a Plot
The plot function has different forms, depending on the input arguments.
If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index
of the elements of
y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus
x.
DSP LABORATORY:
EXPERIMENT#1
10
For example, these statements use the colon operator to create a vector of x
values ranging from
zero to 2, compute the sine of these values, and plot the result.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
%Now label the axes and add a title. The characters \pi create the symbol .
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
DSP LABORATORY:
EXPERIMENT#1
11
sin(x )
sin(x
-.25)
sin(x -.5)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
Axis rescaling:
MATLAB provides automatic scaling. The command axis([xmin. xmax. ymin.
ymax.]) enforces the manual scaling. For example
axis([-10 40 -inf inf])
produces an x-axis scale from - 10 to 40 and an automatic scaling for the y-axis
scale. Typing axis
again or axis(auto) resumes auto scaling.
Stem
If you wish to use information in discrete-time using the stem command can
be useful. It is very similar to plot except it doesnt connect the dots.
The following example creates a stem plot of a cosine function.
y = linspace(0,2*pi,10);
h = stem(cos(y),'fill','-.');
set(h(3),'Color','r','LineWidth',2) % Set base line
properties axis ([0 11 -1 1])
Specifying Line
and Colors
Styles
It is possible to specify color, line styles, and markers (such as plus signs or
circles) when you plot your data using the plot command.
plot(x,y,'color_style_marker') , where color_style_marker is a string containing
from one to four characters (enclosed in single quotation marks)
constructed from a color, a line style, and a marker type:
Color strings are '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.
Omit the linestyle for no line.
The marker types are '+', 'o', '*', and 'x' and the filled marker
types are 's' for square, 'd' for diamond, '^' for up triangle, 'v'
for down triangle, '>' for right triangle, '<' for left triangle, 'p'
for pentagram, 'h' for hexagram, and none for no marker.
Figure
Windows
Graphing functions automatically open a new figure window if there are
no figure windows already on the screen. If a figure window exists, MATLAB
uses that window for graphics output. If there are multiple figure windows
open, MATLAB targets the one that is designated the current figure (the last
figure used or clicked in).
To make an existing figure window the current figure,
you can type :
>> figure(n)
where n is the number in the figure title bar. The results of subsequent
graphics commands are displayed in this window. To open a new figure window
and make it the current figure, type:
>> figure
Exerc ise#1
(a) Generate a matrix of size 5x5 of normally distributed
rd
Exerc is
e#2
nd
column.
Exerc is
e#3
(c) Whats the size of B? Also find the size of B without semicolon
(;).
Define the following discrete time signal using zeros and ones functions
and plot using stem
function.
= )(
Exerc is
e#4
0.8
0
0.2
0 < 10
10 < 20
20
0
Generate and plot 100 samples of the following signals using inspace
function. Label the axiss suitably. Give suitable title to the plots. Use grid on
function in plots. Plot real and imaginary parts of
signal () and use legend function to identify them. Also show 3-D plot of signal ().
Exerc is
e#5
() 10 = ( )
5 5
0.02 =
cos(8
)
where,
t ranges
from 1 to 5. Give the x-axis the title (t sec) and the y-axis the
title (f(t)
volts ).
Repeat using stem function. Then use subplot to combine the two figures
in one figure and
give it the name: difference between plot and stem. Use axis command to show
plots in the range
[-3, 12, -10, 10]