Igital Ignal Rocessing: Lab Contents: Introduction To MATLAB, Getting Started (Reading
Igital Ignal Rocessing: Lab Contents: Introduction To MATLAB, Getting Started (Reading
Igital Ignal Rocessing: Lab Contents: Introduction To MATLAB, Getting Started (Reading
Instructor:
Engr. Nauman Tareen,
Lecturer EE,
CIIT, Abbottabad
WHAT IS MATLAB:
MATLAB® is a high-level language and interactive environment that enables you to
perform computationally intensive tasks faster than with traditional programming
languages such as C, C++, and Fortran.
MATLAB is an interactive system whose basic data element is an array that does
not require dimensioning. It allows you to solve many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it
would take to write a program in a scalar no interactive language such as C or
Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written
to provide easy access to matrix software developed by the LINPACK and EISPACK
projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries,
embedding the state of the art in software for matrix computation.
MATLAB has evolved over a period of years with input from many users. In
university environments, it is the standard instructional tool for introductory and
advanced courses in mathematics, engineering, and science. In industry, MATLAB
is the tool of choice for high-productivity research, development, and analysis.
1
6/3/2013
The way you start the MATLAB program depends on the platform you use:
When you start MATLAB, all the product software from The MathWorks™ that you
are licensed to use, is available. You do not have to start each product separately.
There are alternative ways to start MATLAB, and you can customize startup. For
example, you can change the directory in which MATLAB starts or automatically
execute MATLAB statements upon startup.
To start the MATLAB program on a Microsoft Windows platform, select Start >
Programs > MATLAB > R2009a > MATLAB R2009a, or double-click the shortcut
icon for MATLAB R2009a on your Windows desktop. The shortcut was
automatically created when you installed MATLAB. To start MATLAB from a DOS
window, cd to the directory in which you want to start MATLAB and type matlab at
the DOS prompt.
After starting MATLAB, the desktop opens. Desktop components that were open
when you last shut down MATLAB will be opened on startup.
On Windows platforms, you can start MATLAB from the Windows Explorer tool by
double-clicking a file with one of these extensions: .fig, .m, .mat, and .mdl. MATLAB
starts and opens in an appropriate tool. If MATLAB is already running, the file
opens in an appropriate tool in the existing session.
This startup feature is based on your file type associations for the Windows
operating system. When you installed MATLAB for Windows platforms, you
specified the file types to associate with MATLAB. For example, if you accepted the
default options, double-clicking an M-file in the Windows Explorer tool opens the file
in the MATLAB Editor.
The default option also associates MEX-files and P-files with MATLAB in the
Windows Explorer tool, which assigns the file types an icon for MATLAB. However,
double-clicking a file with a .mex (.mexw32 or .mexw64), or .p extension does not run
or open the file in MATLAB.
2
6/3/2013
MAT-file Opens Import Wizard to load the data into the MATLAB workspace
If you double-click a FIG-file, M-file, MAT-file, or MDL-file and it does not open in ,
and you want it to, try this:
1. In the Windows Explorer tool, right-click a file that has one of the extensions
for MATLAB, for example, myfile.mat.
2. From the context menu, select Open With. If MATLAB is one of the choices,
select it to open myfile.mat in MATLAB.
3
6/3/2013
But If MATLAB is not one of the choices, you will need to associate the file
type with MATLAB using one of these techniques:
3. File associations for the Windows Explorer tool do not affect what happens
when you open one of these file types from within MATLAB. MATLAB acts
on the file using the MATLAB tool associated with that file type. For
example, even if you associate .mat files with the Access application, when
you open a MAT-file from within MATLAB, it opens the Import Wizard to
load the data.
The startup directory is the current directory in the MATLAB application when it
starts. It is convenient if you make the current directory upon startup be a directory
that you frequently use. On Windows and Apple Macintosh platforms, a directory
called userpath is added automatically to the search path upon startup, and is the
default startup directory. The default value for userpath is, for example,
Documents/MATLAB on Microsoft Windows Vista™ platforms. You can specify a
different default value for userpath, or specify a different startup directory.
Accepting the default value for userpath and using it as the startup directory offers
these benefits:
You can store the MATLAB files you work with in one, appropriately-named
location, such as Documents/MATLAB.
Your MATLAB files are readily available upon startup, because the current
directory is always the same, for example, Documents/MATLAB.
You can always run your files because MATLAB automatically adds the
userpath subdirectory to the top of the search path upon startup.
The first time you run a new version of MATLAB, MATLAB automatically
creates the userpath subdirectory if it does not exist.
When you upgrade to a newer version of MATLAB, MATLAB automatically
continues to use the same MATLAB subdirectory and your existing files, with
all of its other benefits.
The default userpath also utilizes the benefits provided by the standard
location in the Windows and Macintosh environments for storing personal
files. Files in the Documents/MATLAB subdirectory (or My
Documents/MATLAB on Windows platforms other than Windows Vista) are
available to you when you use other machines. Because each user has their
own Documents/MATLAB subdirectory, other users, even those using your
machine, cannot access files in your Documents/MATLAB subdirectory.
4
6/3/2013
To set a preference that displays a confirmation dialog box when you quit MATLAB,
select File > Preferences > General > Confirmation Dialogs, select the Confirm
before quitting check box, and click OK. MATLAB then displays the following dialog
box when you quit.
You can also display your own quitting confirmation dialog box using a finish.m
script, as described in the following section.
If MATLAB terminates unexpectedly, you might lose information. After you start
MATLAB again, you can try these suggestions to recover some of the information.
Use the Command History or the file on which it is based, history.m, to run
statements from the previous session. You might be able to approximately
recreate data as it was prior to the termination. For more information, see
Overview of the Command History Window.
If you used the diary function or -logfile startup option for the session in
which MATLAB terminated unexpectedly, you might be able to recover
output.
5
6/3/2013
If you saved the workspace to a MAT-file during the session, you can recover
it by loading the MAT-file. For more information, see Viewing and Loading a
Saved Workspace and Importing Data, and Saving the Current Workspace.
If you were editing a file in the Editor when MATLAB terminated
unexpectedly, and you had the autosave preference enabled, you should be
able to recover changes you made to files you had not saved.
If you were in a Simulink session when a segmentation violation occurred,
and you have the Simulink Autosave Options preference selected, note that
the last autosave file for the model reflects the state of the autosave data
prior to the segmentation violation. Because Simulink models might be
corrupted by a segmentation violation, a model is not autosaved after a
segmentation violation occurs.
Some of the above suggestions refer to actions you might have needed to take during
the session when MATLAB terminated. If you did not take those actions, consider
regularly performing them to help you recover from any future abnormal
terminations you might experience.
DESKTOP
Desktop Overview
In general, when you start the MATLAB program, it displays the MATLAB desktop,
a set of tools (graphical user interfaces or GUIs) for managing files, variables, and
applications associated with MATLAB.
You can change the desktop arrangement to meet your needs, including resizing,
moving, and closing tools. The desktop manages tools differently from documents.
The Command History and Editor are examples of tools, and an M-file is an example
of a document, which appears in the Editor tool.
The first time you start MATLAB, the desktop appears with the default layout, as
shown in the following illustration.
6
6/3/2013
The following tools are managed by the MATLAB desktop, although not all of them
appear by default when you first start. If you prefer a command-line interface, you
can often use equivalent functions to accomplish the same results. To perform the
equivalent of the GUI tasks in M-files, you must use the equivalent functions.
Instructions for using equivalent functions to perform the task are provided with the
documentation for each tool and are typically labeled as Function Alternatives.
7
6/3/2013
You can access many of the desktop menu items using shortcut keys (sometimes
called accelerators or hot keys) for your platform. For example, use the Ctrl+X
shortcut to perform a cut on Microsoft Windows platforms. Many of the menu items
show the shortcuts. Additional standard shortcuts for your platform usually work
but only one is listed with each menu item.
Instructions in the documentation specify shortcuts using the key convention for
Windows platforms, Ctrl+. With key bindings for Apple Macintosh platforms
selected, you use the Command key instead of the Ctrl key. On the Macintosh
platform, to make full use of all keyboard shortcuts, you might need to enable full
keyboard access. To access this option, choose Apple menu > System Preferences,
and click Keyboard & Mouse. Click Keyboard Shortcuts and select Turn full
keyboard access on or off.
You also can use mnemonics to access menu items and buttons, such as Alt+F to
open the File menu. This is not supported on the Macintosh platform. Mnemonics
are listed with the menu item or button. For example, on the File menu, the F in
File is underlined, which indicates that Alt+F opens the menu. In the Profiler, the R
in the Run this code toolbar field is underlined, indicating that Alt+R moves the
cursor to this field.
8
6/3/2013
Note that some versions of the Windows operating system do not automatically show
the mnemonics on the menu. For example, you might need to hold down the Alt key
while the tool is selected to see the mnemonics on the menus and buttons. Use the
Windows Control Panel to set preferences for underlining keyboard shortcuts. See
the Windows documentation for details.
Following are some general shortcuts that are not listed on menu items.
Key Result
Enter The equivalent of double-clicking, Enter performs the default
action for a selection. For example, press Enter while a
statement in the Command History window is selected to run
that statement in the Command Window.
For buttons in tools and dialog boxes, Enter executes the default
button (the button with a border around it). If there is no default
button, press the space bar to execute the active button (the
button with a dotted outline inside it). See Default Button and
Active Button (Button with Focus) for an illustration.
Esc (escape) Cancels the current action. For example, if you select the Edit
menu, the menu items display. Pressing Esc retracts the menu
items. Pressing Esc in a dialog box is the same as selecting the
Cancel button.
Tab Advances to the next button or field in a tool or dialog box.
9
6/3/2013
Key Result
Ctrl+Page Down Moves to the next tool within a group of tools tabbed together. In
a group of documents, moves to next document.
Ctrl+Page Up Moves to the previous tool within a group of tools tabbed
together. In a group of documents, moves to previous document.
Ctrl+F6 Moves to the next tool or document (only for Windows and Sun
Microsystems Solaris™ platforms).
Alt+F4 Closes the desktop and consequently, shuts down the MATLAB
program. Or outside the desktop, closes the active window
(except on Macintosh platforms)
MATLAB HELP
You have to highly rely on MATLAB help throughout and it’s a good habit to use
MATLAB help instead of wandering out on internet and searching for answers. Here
are some steps on how you can access and use MATLAB help.
10
6/3/2013
As you can see in the figure above there is a lot of helping material available on each
and every topic, so no need to panic if you face any sort of problem just refer to
MATLAB help.
11
6/3/2013
You can also search for commands, codes, examples etc by clicking on help >> Index
>> Enter Index term>> (Enter the desired term youneed to search). Enter the
keyword as shown in the preceding figure and you will get a lot of results, select the
appropriate one and you will have all the help in front of you on that specific topic.
For example, the trigonometric function cos (cosine) was searched here and all the
available topics regarding cos were listed after selecting the desired option the
relevant data appeared on screen.
12
6/3/2013
MATLAB stores variables in the form of matrices which are M ×N, where M is the
number of rows and N the number of columns. A 1 × 1 matrix is a scalar; a 1 × N
matrix is a row vector, and M×1 matrix is a column vector. All elements of a matrix
can be real or complex numbers; √−1 can be written as either ‘i’ or ‘j’ provided they
are not redefined by the user.
A matrix is written with a square bracket ‘[]’ with spaces separating adjacent
columns and semicolons separating adjacent rows. For example, consider the
following assignments of the variable x
There are a few notes of caution. Complex elements of a matrix should not be typed
with spaces, i.e., ‘-1+2j’ is fine as a matrix element, ‘-1 + 2j’ is not. Also, ‘-1+2j’ is
interpreted correctly whereas ‘-1+j2’ is not (MATLAB interprets the ‘j2’ as the name
of a variable. You can always write ‘-1+j*2’.
Generating vectors
Vectors can be generated using the ‘:’ command. For example, to generate a vector x
that takes on the values 0 to 10 in increments of 0.5, type the following which
generates a 1×21 matrix
>> x = [0:0.5:10];
13
6/3/2013
Other ways to generate vectors include the commands: ‘linspace’ which generates a
vector by specifying the first and last number and the number of equally spaced
entries between the first and last number, and ‘logspace’ which is the same except
that entries are spaced logarithmically between the first and last entry.
where the ‘:’ here means “take all the entries in the column”. A submatrix of A
consisting of rows 1 and 2 and all three columns is specified by
MATRIX OPERATIONS
+ addition
- subtraction
* multiplication
/ right division
\ left division
^ exponentiation (power)
’ conjugate transpose
14
6/3/2013
An error message occurs if the sizes of matrices are incompatible for the operation.
Division is defined as follows: The solution to A ∗ x = b is x = A\b and the solution to
x ∗ A = b is x = b/A provided A is invertible and all the matrices are compatible.
.* multiplication
./ right division
.\ left division
.^ exponentiation (power)
.’ transpose (unconjugated)
>>A = [1 2; 3 4]
A=
1 2
3 4
>>B=A*A
B=
7 10
15 22
>>C=A.*A
C=
1 4
9 16
Relational operations
15
6/3/2013
== equal to
~= not equal to
MATLAB contains the usual set of flow control structures, e.g., for, while, and if,
plus the logical operators, e.g., & (and), | (or), and ~ (not).
Math functions
MATLAB comes with a large number of built-in functions that operate on matrices
on an element-by element basis. These include:
sin sine
cos cosine
tan tangent
exp exponential
16
6/3/2013
PLOTTING
plot(t,x); %Plot x vs t
hist Histogram
Customization of plots
17
6/3/2013
There are many commands used to customize plots by annotations, titles, axes
labels, etc.
subplot(a,b,c) Create an a × b matrix of plots with c the current figure orient Specify
orientation of a figure.
GENERAL INFORMATION
MATLAB is case sensitive so "a" and "A" are two different names.
Comment statements are preceded by a "%".
You can make a keyword search by using the help command.
The number of digits displayed is not related to the accuracy. To change the
format of the display, type
format short e for scientific notation with 5 decimal places,
format long e for scientific notation with 15 significant decimal places and
format bank for placing two significant digits to the right of the decimal.
The commands who and whos give the names of the variables that have been
defined in the workspace.
The command length(x) returns the length of a vector x and size(x) returns
the dimension of the matrix x.
18
6/3/2013
INTRODUCTION
Informally the terms matrix & array are often used interchangeably. Matrix is the
two dimensional array of real & complex numbers.
Creating a Matrix:
1 1 1
>> A= 1 2
3
1 3 6
A A'
1 1 1
A= 1 2 3
1 3 6
1 1 1
A ' = 1 2 3
1 3 6
Note: from above we can easily say that A & A ' are equal. So matrix A is symmetric
matrix.
PASCAL (N) is the Pascal matrix of order N: a symmetric positive definite matrix
with integer entries, made up from Pascal's triangle. Its inverse has integer entries.
>> A=pascal(3)
A= 1 1 1
1 2 3
1 3 6
19
6/3/2013
MAGIC (N) is an N-by-N matrix constructed from the integers 1 through N^2 with
equal row, column, and diagonal sums.Produces valid magic squares for all N > 0
except N = 2.
>> B=magic(3)
8 1 6
B 3 5 7
4 9 2
8 3 4
B' 1 5 9
6 7 2
Type the following command in MATLAB and read carefully the whole help.
>>help rand:
FIX(X) rounds the elements of X to the nearest integers towards zero. See also
FLOOR, ROUND, CEIL.
Now type
9 4
C 2 8
6 7
20
6/3/2013
Matrix Addition and Multiplication is done element by element. This means that
both matrices should have same number of rows and columns, so they can be added
and subtracted.
1+2j 3
d
7 5j
2 3 j 5+5j
c
0 1-8j
>>f=d+c
3+5j 8+5j
f=
0 1-3j
Here also real part is added to real one and imaginary part with the imaginary part.
We use conj command to calculate the complex conjugate of each complex element in
the matrix.
Type
1+2j
g
3+4j
>> h=conj (g)
1 2 j
h
3 4 j
Matrix Powers
Let suppose you want to multiply a matrix A with itself P times. Then write the following
command in matlab.
>>A = [1 2 3; 4 5 6; 7 8 9];
>>P=2;
>>B=A^P
21
6/3/2013
1 2 3
A 4 5 6
7 8 9
30 36 42
B 66 81 96
102 126 150
* Note you can also multiply matrix and also vector element by element.
>>A = [1 2 3; 4 5 6; 7 8 9];
>>P=2;
>>C=A. ^P
1 2 3
A 4 5 6
7 8 9
1 4 9
C 16 25 36
49 64 81
Let Z=A+Bj;
And
Accessing the element from inside a vector or matrix is the most powerful advantage
of the MATLAB over any other computer language. Let’s see how this is done by
MATLAB.
>> K=10:10:100;
K= [10 20 30 40 50 60 70 80 90 100]
>>K1=K (1:5)
22
6/3/2013
>>K2=K (3:8)
>>P=Pascal (3)
1 1 1
P= 1 2 3
1 3 6
>> P1 =P(:, 2)
1
P1= 2
3
>>P2=P(1,:)
P2= 1 1 1
1 2 3 4 5
M 2 4 6 8 10
3 6 9 12 15
4 6 8
M1
6 7 12
>>M (:) % this command will convert the matrix into vectors such that
columns are taken first. Try it yourself & also below given commands.
>>K=1:2:10
>>f=5:5:50;
23
6/3/2013
M=ej11п/4 j (cosө+jsinө)
M1= (1-j) 10
Now if we want to solve these expressions by using the matlab, then we use these
commands are techniques.
>>pi=3;
Plots in MATLAB are generated using the plot function. Try the below command.
Now as we already know from our previous knowledge that complex numbers
corresponds to x = a+bj
So MATLAB provides the ‘real’ & ‘imag’ function to separate the real &imaginary
parts of a complex number.
>> x=2+7j;
>> xr=real(x);
>> xi=imag(x);
>> Plot (xr, xi,'x'); % Here ‘x’ defines the shape of the data point.
f (t) =3ei3пt
We could use
24
6/3/2013
t=0:0.001:1;
f=3*exp (j*3*pi*t);
25
6/3/2013
LAB ASSIGNMENT 01
Q.1. Create a symmetric matrix ‘m’ with five rows and five columns. Calculate its
transpose and verify that the matrix is symmetric by observing that m=m’.
Q.2. Create a random matrix with 4 rows and 5 columns. The matrix values
should be integer b/w (0—100), than change any 2 rows values by ‘17’.
Q.3. Use your knowledge to define a vector by incrementing and also cascade
more than one vector to form a matrix try to make a matrix with the following
properties.
(2) First row of matrix should contain even number b/w (0—10)
(3) Second row of matrix should contain odd number b/w (11—20)
Q.4.
Define
1+2j 3 2+3j 5+5j
d= & e=
7 5j 0 1-8j
and calculate
(a) c=d+e
(b) c=d-e
(c) c=d*e
(d) c=d/e
Y1=3*exp (3*pi*t);
Y2=3*exp (0.3*pi*t);