



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Discrete Signal Processing (Introduction to Matlab)
Typology: Lecture notes
1 / 27
This page cannot be seen from the preview
Don't miss anything!




















Instructor: Dr. Ihsan Ullah, DEE, CIIT, Abbottabad
Lab Contents: Introduction to MATLAB, Getting started (Reading Assignment), Vectors, Scalars and Matrices, Basic Arithmetic operations, Mathematic functions, and Plotting.
Department of Electrical Engineering,
COMSATS Institute of Information technology, Abbottabad
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.
The MATLAB high-performance language for technical computing 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 Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface building
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.
MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. You can add on toolboxes for signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many other areas.
File Type and Resulting Action
File Type Result
FIG-file Opens file in figure window
M-file Opens file in Editor
MAT-file Opens Import Wizard to load the data into the MATLAB workspace
MDL-file Opens file in a Simulink® model window
MEX-file Displays icon for MATLAB in Windows Explorer tool
P-file Displays icon for MATLAB in Windows Explorer tool
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:
But If MATLAB is not one of the choices, you will need to associate the file type with MATLAB using one of these techniques:
Utility to Change File Associations for Windows Platforms Changing File Associations for the MATLAB Program from the Windows Environment
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.
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.
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.
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.
Desktop Tool Description
Command History View a log of or search for the statements you entered in the Command Window, copy them, execute them, and more.
Command Window Run MATLAB language statements.
Current Directory View files, perform file operations such as open, find files and
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.
In the Command Window, completes a statement if the tab completion preference is selected.
Space bar For buttons in tools and dialog boxes, activates the active button. See Default Button and Active Button (Button with Focus) for an illustration of selecting default and active buttons using keys.
Use these keys on the numeric keypad to expand and collapse items in tree views. The Help browser Help Navigator pane and the Command History window use tree views. Use + to expand the selected item, use - to collapse the selected item, and use * to recursively expand it, meaning open all items contained in the selected item.
Alt+S Displays the Start button menu (except on Macintosh platforms).
Alt+Y Provides access to the current directory field in the toolbar (except on Macintosh platforms).
Ctrl+Tab Moves to the next open tool in the desktop, or to the next open group of tools tabbed together.
Ctrl+Shift+Tab Moves to the previous open tool or group of tabbed tools in the
Key Result
desktop.
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)
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. (Just in case you need to search the internet for help, you can always get help at www.mathworks.com ).
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.
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
Real scalar >> x = 5 Complex scalar >> x = 5+10j (or >> x = 5+10i) Row vector >> x = [1 2 3] (or x = [1, 2, 3]) Column vector >> x = [1; 2; 3] 3 × 3 matrix >> x = [1 2 3; 4 5 6; 7 8 9]
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‟.
Some of the important operations on complex numbers are illustrated below.
Complex scalar >> x = 3+4j Real part of x >> real(x) = 3 Imaginary part of x >> imag(x) = 4 Magnitude of x >> abs(x) = 5 Angle of x >> angle(x) = 0. Complex conjugate of x >> conj(x) = 3 - 4i
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
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.
Addition and subtraction involve element-by-element arithmetic operations; matrix
multiplication and division do not. However, MATLAB provides for element-by-
element operations as well by prepending a „.‟ before the operator as follows:
.* multiplication
./ right division
.\ left division
.^ exponentiation (power)
.‟ transpose (unconjugated)
The difference between matrix multiplication and element-by-element multiplication
is seen in the following example
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
The following relational operations are defined:
< less than
<= less than or equal to
greater than
= greater than or equal to
== equal to
~= not equal to
These are element-be-element operations which return a matrix of ones (1 = true)
and zeros (0 = false). Be careful of the distinction between „=‟ and „==‟.
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).
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
asin inverse sine
acos inverse cosine
atan inverse tangent
exp exponential
log natural logarithm
log10 common logarithm
sqrt square root
abs absolute value (magnitude of a number)
round round towards nearest integer.
There are many commands used to customize plots by annotations, titles, axes
labels, etc.
A few of the most frequently used commands are
xlabel Labels x-axis
ylabel Labels y-axis
title Puts a title on the plot
grid Adds a grid to the plot
axis Allows changing the x and y axes
figure Create a figure for plotting
hold on Allows multiple plots to be superimposed on the same axes
hold off Release hold on current plot
close(n) Close figure number n
subplot(a,b,c) Create an a × b matrix of plots with c the current figure orient Specify
orientation of a figure.
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.
Informally the terms matrix & array are often used interchangeably. Matrix is the
two dimensional array of real & complex numbers.
MATLAB contain many functions that create different type of matrices.
>> A=
matrix.
In MATLAB we can use the command Pascal to create 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