Sei sulla pagina 1di 27

DIGITAL SIGNAL PROCESSING

Lab Contents: Introduction to MATLAB, Getting started (Reading


Assignment), Vectors, Scalars and Matrices, Basic Arithmetic operations,
Mathematic functions, and Plotting.

Instructor:
Engr. Nauman Tareen,
Lecturer EE,
CIIT, Abbottabad

Department of Electrical Engineering,


COMSATS Institute of Information Technology, Abbottabad
6/3/2013

DIGITAL S IGNAL P ROCESSING

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.

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.

1
6/3/2013

Overview of Starting the MATLAB Program

The way you start the MATLAB program depends on the platform you use:

 On Microsoft® Windows® platforms, start MATLAB by double-clicking the


MATLAB R2009a shortcut on your Windows desktop.

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.

Starting the MATLAB Program from the Windows Desktop

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.

Starting the MATLAB Program from an M-File or Other File Type


on Windows Platforms

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

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:

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:

 Utility to Change File Associations for Windows Platforms


 Changing File Associations for the MATLAB Program from the
Windows Environment

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.

Startup Directory for the MATLAB Program

What Is the Startup Directory?

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

WAYS TO QUIT THE MATLAB PROGRAM


To quit the MATLAB program at any time, do one of the following:

 Click the Close box in the MATLAB desktop.


 Select Exit MATLAB from the desktop File menu.
 Type quit at the Command Window prompt.

MATLAB closes after

 Prompting you to confirm quitting, if that preference is specified.


 Prompting you to save any unsaved files.
 Running the finish.m script, if it exists in the current directory or on the
search path.

Confirm Quitting the MATLAB Program

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.

Recovering Data After an Abnormal Termination

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

About the Desktop

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

Summary of Desktop Tools

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

7
6/3/2013

Desktop Tool Description


Browser file content, and manage and tune your files.
Editor Create, edit, debug, and analyze M-files (files containing
MATLAB language statements).
Figures Create, modify, view, and print figures generated with
MATLAB.
File and Directory View line-by-line differences between two files.
Comparisons
Help Browser View and search the documentation and demos for all your
MathWorks products.
Profiler Improve the performance of your M-files.
Start Button Run tools and access documentation for all your MathWorks
products, and create and use shortcuts for MATLAB.
Variable Editor View array contents in a table format and edit the values.
Web Browser View HTML and related files produced by MATLAB.
Workspace Browser View and make changes to the contents of the workspace.

Keyboard Shortcuts (Accelerators or Hot Keys) and Mnemonics

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.

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.
+ or - or * on Use these keys on the numeric keypad to expand and collapse
numeric keypad 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
desktop.

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 VARIABLES — SCALARS, VECTORS, AND


MATRICES

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

Complex number operations

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.9273
 Complex conjugate of x >> conj(x) = 3 - 4i

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.

Accessing vector elements


Elements of a matrix are accessed by specifying the row and column. For example, in
the matrix specified by A = [1 2 3; 4 5 6; 7 8 9], the element in the first row and third
column can be accessed by writing

>> x = A(1,3) which yields 3

The entire second row can be accessed with

>> y = A(2,:) which yields [4 5 6]

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

>> z = A(1:2,1:3) which yields [1 2 3; 4 5 6]

MATRIX OPERATIONS

MATLAB contains a number of arithmetic, relational, and logical operations on


matrices.

Arithmetic matrix operations


The basic arithmetic operations on matrices (and of course scalars which are special
cases of matrices) are:

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

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

Relational operations

The following relational operations are defined:

15
6/3/2013

< 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 ‘==’.

Flow control operations

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

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.

ceil round towards plus infinity.

16
6/3/2013

floor round towards minus infinity.

PLOTTING

MATLAB contains numerous commands for creating two- and three-dimensional


plots. The most basic of these commands is ‘plot’ which can have multiple optional
arguments. A simple example of this command is to plot a function of time.

t = linspace(0, 8, 401); %Define a vector of time from ...

0 to 8 s with 401 points

x = t.*exp(-t).*cos(2*pi*4*t); %Define a vector of x values

plot(t,x); %Plot x vs t

xlabel(’Time (s)’); %Label time axis

ylabel(’Amplitude’); %Label amplitude axis

Simple plotting commands

The simple 2D plotting commands include

plot Plot in linear coordinates as a continuous function

stem Plot in linear coordinates as discrete samples

loglog Logarithmic x and y axes

semilogx Linear y and logarithmic x axes

semilogy Linear x and logarithmic y axes

bar Bar graph

errorbar Error bar graph

hist Histogram

polar Polar coordinates

Customization of plots

17
6/3/2013

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.

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.

COMPLEX NUMBERS AND MATRIX MANIPULATION

18
6/3/2013

INTRODUCTION

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.

Creating a Matrix:
1 1 1

>> A= 1 2

 3
1 3 6 

Creating a Symmetric Matrix:


For a symmetric matrix ‘A’ the matrix ‘A’ and its transpose A ' are equal i.e.

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.

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

Creating a Non Symmetric Matrix


If A  A '

19
6/3/2013

Then matrix is non-symmetric:

We use magic command in MATLAB to create such type of matrix.

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

Since here B  B ' hence the matrix B is non symmetric.

Creating matrix with Random integer

Type the following command in MATLAB and read carefully the whole help.

>>help rand:

>> help fix

FIX Round towards zero.

FIX(X) rounds the elements of X to the nearest integers towards zero. See also
FLOOR, ROUND, CEIL.

Now type

>> C=fix (10*rand (3, 2))

9 4
 
C   2 8
6 7
 

Here C is the generated matrix with 3 rows and 2 columns.

Matrix Addition and Multiplication

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.

>> d= [1+2j 3; 7 5j]

>> c= [2+3j 5+5j; 0 1-8j]

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

Calculating complex Conjugate

We use conj command to calculate the complex conjugate of each complex element in
the matrix.

Type

>>help conj % for more information about conj command

>> g = [1+2j; 3+4j];

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
 

Extracting Real & Imaginary Part From Complex Number

Let Z=A+Bj;

Then Z (real) =real (A);

And

Z (imaginary) = imag (A);

Accessing elements in Vectors/Matrices

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

K1= [10 20 30 40 50]

>>K2=K (3:8)

K2= [30 40 50 60 70 80]

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

M=[1:5; 2:2:10; 3:3:15]

1 2 3 4 5 
M   2 4 6 8 10
3 6 9 12 15 

>>M1=M (2:3, 2:4)

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

Evaluating Complex Variables & Expressions

Consider the following two expressions that we want to write in matlab.

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.

>> M=j*exp (j*11*pi/4)% Here pi is the predefined variable in Matlab. If we want


to change its value to 3, then we can use the command

>>pi=3;

Now if we want to restore the default value then type

>> clear pi;

>>M1= (1-j) ^10;

Plotting Complex value functions in MATLAB

Plots in MATLAB are generated using the plot function. Try the below command.

>> help plot

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.

For more clearance of mind try to absorb the following example.

>> x=2+7j;

>> xr=real(x);

>> xi=imag(x);

>> Plot (xr, xi,'x'); % Here ‘x’ defines the shape of the data point.

Generating Complex Functions

Generating complex function can be explained from the following example.

f (t) =3ei3пt

For t=01 with 0.001 increments

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

Hint: Use commands fix & rand

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.

(1) Matrix should contain 2 rows.

(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

Q.5. Plot the function

Y1=3*exp (3*pi*t);

Y2=3*exp (0.3*pi*t);

Choose t from (0---1) with increment of 0.001

 Hard copy of the Lab Assignment has to be submitted in the


coming Lab next week.
 The report should be up to standards in terms of the
formatting i.e. properly aligned, justified, proper
26
paragraph/line spacing, font size and font color.
 Use a standard Front page uploaded on cuonline.
 Lab reports not up to standard will not be accepted.

Potrebbero piacerti anche