Sie sind auf Seite 1von 98

See

discussions, stats, and author profiles for this publication at: https://www.researchgate.net/publication/288824058

MATLAB for Engineering Applications

Book December 2014

CITATIONS READS

0 3,793

1 author:

Abdullah Ali Alshehri


King Abdulaziz University, Faculty of Engineering-Rabigh
29 PUBLICATIONS 43 CITATIONS

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Multi-perspective seismogram anomaly predictions in one-dimensional non-stationary signals using


wavelets and neural networks. View project

Energy-conversion View project

All content following this page was uploaded by Abdullah Ali Alshehri on 30 December 2015.

The user has requested enhancement of the downloaded file.


King Abdulaziz University
Faculty of Engineering-Rabigh
Electrical Engineering

MATLAB for
Engineering
Applications
FIRST EDITION

Dr. ABDULLAH ALSHEHRI


Table of Contents
Part I Fundamentals of MATLAB

Chapter 1 Introduction to MATLAB

1.1 How to Start and Quit MATLAB


1.2 Variables
1.3 Output Formats
1.4 Numbers and Arithmetical Operations in MATLAB
1.5 Character String
1.6 Functions
1.7 Basic Arithmetical Operations
1.8 Utility Matrix
1.9 Exporting to Excel Spreadsheet Files
1.10 Long Command Lines
1.11 Demos
1.12 Interrupting a Running Program
1.13 Saving and Reloading
1.14 Getting Help in MATLAB
1.15 Printing
1.16 MATLAB Commands List

Chapter 2 MATLAB Graphics


2.1 Graphics
2.2 Logarithmic Plots
2.3 Plots with Special Graphics
2.4 Pie Plots
2.5 3-D Plots
2.6 Histograms
2.7 Advanced MATLAB Graphics
2.8 Printing Graphics
2.9 MATLAB Commands List

Chapter 3 Programming in MATLAB


3.1 The M-file
3.2 Inline Functions and the Feval Command
3.3 Logical Operators and Control Flow
3.4 Strings
3.5 Cell Arrays
3.6 Rounding to Integers
Part II Analytical and Numerical Methods Using MATLAB

Chapter 4 Linear Algebra Aspects and Solution Methods of Systems


of Linear Equations

4.1 Introduction
4.2 Matrices and Vectors in MATLAB
4.3 Solving Systems of Linear Equations
4.4 Special Functions and Applications
4.5 Inverse of Matrix
4.6 Determinants
4.7 Left-Division Method
4.8 Gauss Elimination Method
4.9 LU Decomposition Method
4.10 Vectors
4.11 Real Vector Spaces
4.12 Matrix and Eigenvalue Problem
4.13 Coding and Decoding
4.14 Summary List of Special Characters and MATLAB Functions

Chapter 5 Numerical Analysis

5.1 Introduction
5.2 Regression and Data Fitting
5.3 Interpolation
5.4 Non-Linear Solution Methods
5.5 Ordinary Differential Equations

Chapter 6 Mathematical Transformations

6.1 Introduction
6.2 Fourier Transform
6.3 Z-Transform
6.4 Discrete Fourier Transform
6.5 Fast Fourier Transform FFT
6.6 Laplace Transform

Part III Engineering Applications and MATLAB Simulations

Chapter 7 Electrical Circuit Analysis

7.1 Introduction
7.2 Ohm's Law
7.3 AC Circuits
7.4 Thevenins Theorem:
7.5 Maximum Power Transfer Theorem
7.6 Nodal Analysis Example
7.7 KVL and KCL Analysis
7.8 Mesh Current Analysis

Chapter 8 Controller Design Techniques

8.1 Controller Design Steps


8.2 Check of Controlled System Stability
8.3 Power System Controller Design Techniques
8.4 Gain and Phase Margins
8.5 Root Locus and Frequency Response Program
8.6 Controller Design Based on System State Space Feedback Techniques
8.7 Designing with Pole Placement Techniques

Chapter 9 Mechanical and Control Systems Applications

9.1 Introduction
9.2 Train Systems
9.3 Modeling Cruise Control Systems
9.4 DC Motor Speed Modeling
9.5 Chemical Engineering Applications

Chapter 10 Communications and Signal Processing

10.1 Introduction
10.2 Waveforms Generations
10.3 Filters Implementations
10.4 Fourier Transform
10.5 Inverse Fourier Transform
10.6 Time-frequency Analysis
10.7 Spread Spectrum Communication Systems
10.8 Wireless Communications
10.9 Multipath Channel Modeling
10.10 Wavelet Transform
10.11 Artificial Neural Network

Appendix Simulink Basic Tutorial

References
Preface

The ultimate goal of this book is to provide the reader with the fundamental skills and
knowledge required to use MATLAB for the simulation of engineering systems in a very
practical approach supported by exercises and real applications. It is intended for users
(engineers, applied engineers, mathematicians, etc.) who are running a professional
version of MATLAB and have basic understanding of math, linear algebra and numerical
analysis. The book assumes no prior knowledge of MATLAB and its applications in the
field of engineering and applied mathematics and numerical analysis. We believe that the
contents of this book will provide readers with the necessary knowledge and practical
skills to use MATLAB in the simulation and testing of algorithms for different problems
in the fields of applied science, engineering, and mathematics.

The book introduces the layout of MATLAB and its environment as an important
introductory step. Then we describe the concepts and fundamental functions of
MATLAB, using algebraic and arithmetic operations as a basis for its application. We try
to show the reader the power of MATLAB and how to simulate and write functions from
different engineering and applied math contexts and to produce illustrative results with
different formats. In later chapters the reader learns how to simulate mathematical
transformation methods such as Laplace, Fourier, and Z-transformations in MATLAB
using real engineering applications. These engineering applications include control
systems, communications, signal processing, mechanical, chemical, and electric circuit
analysis.

Chapter 1 introduces the fundamentals of MATLAB and basic functions such as


arithmetical operations, saving, plotting and printing. Chapter 2 explains the simple and
advanced tools for producing different types of graphics. Chapter3 provides the reader
with the necessary programming skills with m-file using control flow, relations, logical
operators, strings, cell arrays, and special functions. Chapter 4 focuses on linear algebra
including matrix and vector operations, solving systems of linear equations, eigenvalues
and determinants. Chapter 5 applies MATLAB to solve numerical analysis operations
such as non-linear equations, interpolation, regression, and data fitting. Chapter 6
explains the MATLAB implementation of the more popular mathematical
transformations such as Fourier and Fast Fourier, Z-transform, and Laplace transforms.
Chapters 7 to 10 provide applications from the different fields of engineering and their
MATLAB simulations, including electrical circuits, control systems, mechanical systems,
communications, and signal processing. The Appendix contains a tutorial on Simulink
with simulations of different engineering applications.
About the Author

Abdullah A. Alshehri is Assistant Professor in the Electrical Engineering Department at


King Abdulaziz University-Rabigh KAU, Saudi Arabia. He was born in 1964 in Saudi
Arabia. In 1993 he received his B.S. in Electrical Engineering from the University of
Detroit, MI, USA. He received his M.S. and Ph.D. in Electrical Engineering from the
University of Pittsburgh, PA in 1999 and 2004 respectively. He has been an IEEE
member since 1992. From 2005 to 2010 he worked as Assistant Professor at the College
of Telecom and Electronics CTE and Jeddah College of Technology JCT, Saudi Arabia.
In December 2010, he joined the Electrical Engineering Department at King Abdulaziz
University-Rabigh. His areas of interests are signal processing and its applications in
spread spectrum and wireless mobile communication schemes such as WCDMA and
CDMA. They also include wavelet transform, time-frequency analysis, and statistical
signal processing.

Acknowledgments
This book was funded by the Deanship of Scientific Research (DSR), King Abdulaziz
University, Jeddah, grant no.(421\829\1433). The author would hereby like to
acknowledge with thanks DSR technical and financial support.

The author would also like to extend his gratitude to Dr Yousef S. Mobarak for his
contribution to Chapter 8, and Engineer Nizamudheen for his assistance with data
collection, editing and preparing the Simulink tutorial in the Appendix.
PART I

Fundamentals of
MATLAB
Chapter 1

Introduction to MATLAB
Topics in this chapter include using the Command Window to perform arithmetical
operations, using numbers, plotting graphs, writing long command lines, interrupting a
running program, saving, reloading, using help, demos, and printing results in
MATLAB.
MATLAB is acknowledged as the leading numerical computing environment and
programming language for engineering and applied mathematics. It allows easy matrix
manipulation, implementation of algorithms, creation of data, and plotting of functions
and graphical results. Furthermore, users can easily interface MATLAB with programs in
other languages. The MATLAB Simulink platform adds model-based design and
graphical multidomain simulation for dynamic and embedded systems. MathWorks
claims that MATLAB is used by millions of people throughout industry and the academic
world.
Before we consider MATLAB tools and techniques, it is important to give a brief
summary of what MATLAB is and how it started. MATLAB derives from the "matrix
laboratory" invented in the late 1970s by Cleve Moler, a professor at the University of
New Mexico. It soon spread to other colleges and universities in the USA and found a
strong audience within the community of applied engineering and mathematics. Its
commercial potential was recognized by control engineer Jack Little in 1983 during
Moler's visit to Stanford University. He joined Moler and Steve Bangert and started to
rewrite MATLAB in C. In 1984 they founded MathWorks to continue its development.
Control design engineers were the first to adopt MATLAB but it quickly spread to many
other engineering fields such as mechanical, civil, chemical, communication, and image
and signal processing. It is now used in finance and applied mathematics for teaching
linear algebra and numerical analysis.

1.1 How to Start and Quit MATLAB

Later versions of MATLAB come with a graphical interface which makes working with
MATLAB more attractive than before. To start MATLAB double click on the MATLAB
icon from the desktop. The graphical user interface (GUI) which comes with MATLAB
is important and we recommend the reader to take a look at it before beginning work.
Figure 1.1 shows MATLAB's graphical user interface, which contains the command
window and bar menu. The graphical interface provides users with all the abilities
required for all functions as they make the appropriate selection: debugging, saving,
printing, sorting, graphing, editing, importing, exporting, etc.
Figure 1.1: MATLAB graphical user interface

MATLAB Command Window is the place where commands are interred. It allows the
user to clear all interred commands using the clc command.

To quit MATLAB and leave the current session type quit or exit at the prompt.

1.1.1 Current Folder Window


In Figure 1.1, the left-most panel shows the files and folders in the current folder. The
files being saved will be moved to this location. The current default folder is listed on the
top panel. The current folder can be changed by browsing from the top drop-down list as
shown in Figure 1.2 below.
Figure 1.2: Drop-down current folder window

1.1.2 Document Window


A new variable can be created from a document window; an existing variable can be
modified, avoiding the traditional method of manual editing. The document window
opens up a variable editor window while creating a new variable or modifying an existing
one. Arrays, matrices and any type of variable can be modified or created in the same
way (see Figure 1.3 below).
Figure 1.3: Document window with variable editor

1.1.3 Graphics Window


When it comes to output by means of plots, graphs and such, the graphic window comes
into the picture. The Figure window in MATLAB displays the figure or graph invoked
on the screen. By means of this, one can modify the plot or figure, and can add/remove
labels, titles, legends, and so on. Figure 1.4 shows a sample figure window with some
editing options.
Figure 1.4: Graphics window with editing menu

1.1.4 Workspace Window


In MATLAB, the values are stored by means of variables. The workspace window keeps
track of all the variables in an existing program. The workspace window contains each
variable and its details such as names, value, type and so on. A sample workspace
window is shown below in Figure 1.5.
Figure 1.5: Workspace window listed with a few variables

1.1.5 Editor Window


Until now, we have focused on the command window to execute commands. The
command window makes MATLAB interactive as it gives the results instantly. However,
this command window is not always suitable for a programmers needs. If a program
goes beyond a few lines of code, it is a tedious task to edit and modify the program using
the command window. MATLAB has come up with a solution to this problem by
introducing an Editor window where one can write the whole program and save the
codes and run as and when required. The window in Figure 1.6 depicts a typical
MATLAB Editor window.
Figure 1.6: Editor Window with Run Button
The files created by Editor Window are known as M-files. An editor window can be
opened up by using edit command in the command window or by selecting the New
script file from
File -> New menu or clicking the New Script button on the Toolbar menu (Figure 1.7).

Figure 1.7: Opening up a new Editor window


1.1.6 MATLAB Help Window
MATLAB provides an extensive Help facility to its users. It is well suited for basic
MATLAB users and advanced users as it offers practical examples. Search and demo are
also available.
A typical MATLAB help window is shown in Figure 1.8.

Figure 1.8: Help window with search option

1.2 Variables
Variable names comprise characters including letters and numbers. For any expression a
variable name must be given otherwise the variable ans will be given as the variable
name.

For simple computations the user needs to type the command first followed by the Enter
key

s = 1 + 5
s =
6
ross = cos(pi/4)
ross =
0.7071
where the trigonometric function cosine and the constant pi are used.

The results of the previous computations are automatically saved in variables with their
names. To recall them during a current MATLAB session, the user should type their
names followed by the Enter key,

s
s = 6
ross
ross = 0.7071

The variable ans will be assigned if no variable name has been specified. For example,

100/cos(pi/3)
result in
ans = 200.000

1.3 Output Format


MATLAB can display in the Command Window the different formats available. Table
1.1 below shows some of the different types of formats which can be used.

Table 1.1 Numeric formats


Command Description
Format short Four decimal digits ; 5.6745
Format long 16 digits 17.2484029463547s
Format short e Five digits (four decimal + exponent); 6.3792e+03
Format long e 16 digits (15 decimals + exponent
Format bank Two decimal digits; 14.25
Format + Positive, negative, or zero; +.
Format rat Rational approximation; 43/7.

The short format is the default one in MATLAB. For this format, four digits are
displayed after the decimal point. To display a different format, the user clicks on File,
then selects Preference, and from the list selects the desired format required before
clicking on Apply followed by OK. Different formats can be selected. For example,

format long
changes current format to long format.
The result is that more digits will be displayed
ross
ross =
0.70710678118655

To go back to default format, type

format short
ross
ross =
0.7071

To close MATLAB session type exit or quit on the command window and then press
Enter key. Another way of exiting MATLAB is by selecting File from the toolbar and
clicking on Exit MATLAB. It should be borne in mind that all unsaved data residing in
the MATLAB Workspace will be lost.

1.4 Numbers and Arithmetical Operations in MATLAB


For arithmetical operations in MATLAB, we use three types of numbers:

real numbers
integers
complex numbers

Integer numbers are entered without the decimal point

xi = 20
xi =
20

For the decimal numbers four digits are displayed

xr = 20.01
xr =
20.0100

As regards the smallest and largest positive numbers, the variables realmin and realmax
denote them respectively. For example,

realmin
ans =
2.2251e-308

The rectangular form is the only way to represent complex numbers in MATLAB. The
imaginary unit is usually denoted by the letters j or i where j or i=sqrt(-1)
i
ans =
0 + 1.0000i

Table 1.2 shows a list of complex functions used in MATLAB with descriptions of the
conversion between polar and rectangular forms.

Table 1.2 list of functions used for complex values


Operation Description
C=a+ib Rectangular form
real(c) Real part of c
Image(c) Imaginary part of c
Angle(c) Phase angle of c
Abs(c) Absolute value of c
Conj(c) Conjugate of c
c=K*exp(j*) Converts K to the rectangular form

In addition, three distinct variables are used in MATLAB to represent the non-numbers
-Inf
Inf
NaN

-Inf and Inf variables are representations of positive and negative infinity as defined by
IEEE. Infinity is obtained by dividing by zero or at the overflow. NaN denotes a not-a-
number obtained from undefined operations.

1.5 Character String


Character string is a sequence of characters and is called text variable

c=Happy

c=
Happy

More text variables can be augmented

Cs=[c,Smile]

Cs =
Happy Smile
1.6 Functions
Fortunately, most of the standard functions are included in MATLAB and have a separate
code. These functions include sin, cos, log, exp, sqrt, and many others. For example,

cos(pi/4)

ans =

0.7071

1.7 Basic Arithmetical Operations


There are five arithmetical operations which can be performed in MATLAB. They are
shown in Table 1.3.

Table 1.3 Symbols of arithmetical operations


Operation Symbol
Multiplication *
Exponentiation ^
Addition +
Subtraction -
Division /or\

Note that there are two operators for division each with different function

rd = 20/3
rd =
6.6667

ld = 20\3
ld =
0.1500

1.7.1 Vector Operations


Creating vectors in MATLAB is simple. Each element of the vector is entered and
separated by space inside brackets and a variable name given. For example, writing the
following vector into the MATLAB command window
a = [1 3 5 8 1 5 4 2 2]

will give
a =
1 3 5 8 1 5 4 2 2

Let us create a short vector with elements evenly spaced with increments of three
between zero and 12:

s = 0:3:12
s =
0 3 6 9 12

Manipulating vectors is an easy process in MATLAB. Adding a scalar to a vector


essentially means adding it to each element in that vector. For example,

b = a + 3

b =
4 6 8 11 4 8 7 5 5

A vector is a row or column array

A=[1; 2; 3; 4]

A=
1
2
3
4

To create a vector of ones or zeros we use these two commands

B=zeros(1,5)
B=
0 0 0 00

Z=ones(1,5)
Z=
1 1 1 1 1

Adding two vectors of the same length is a straightforward process

c = a + b

c =
5 9 13 19 5 13 11 7 7

Similarly, for the subtraction of two vectors of the same length


d = b - a
d =
3 3 3 3 3 3 3 3 3

1.7.2 Characteristic Polynomials


In MATLAB, polynomials are represented by vectors. In order to create a polynomial's
vector simply one enters the polynomial coefficients into the vector in descending order.
For example, consider the polynomial

Now inter the polynomial coefficients as a vector


x = [1 3 -15 -2 9]

x =
1 3 -15 -2 9
A vector of length n+1 can be interpreted in MATLAB as an nth order polynomial. One
needs to inter zeros for any missing coefficients. For example,

y x4 1
is represented in MATLAB as

y = [1 0 0 0 1]

The function polyval can be used to find the value of the polynomial.

Let us try to find the polynomial of the above equation using the polyval function at
s=2

p = polyval([1 0 0 0 1],2)

p =
17

The polynomial roots can be extracted using the command roots. Consider again the
high-order polynomial

The roots can be found using this command

roots([1 3 -15 -2 9])


ans =
-5.5745
2.5836
-0.7951
0.7860

When two polynomials are multiplied together, the product is simply the convolution of
their coefficients. The function conv from MATLAB will solve it

r = [1 2];
s = [1 4 8];
x = conv(x,y)

x =
1 6 16 16

We can use deconv function for dividing two polynomials. It will return the result and
the remainder. Now let us divide x by s and see if we get r

[xx,R] = deconv(x,s)
xx =
1 2
R =
0 0 0 0

The results are values of the vector r.

1.7.4 Matrix Operations

Matrices can be entered into MATLAB in a similar way to vectors. The rows of the
matrix are separated by a semicolon (;)

B = [2 1 3 4;7 7 9 8;2 1 11 12]

B =
2 2 3 4
7 7 9 8
2 1 11 12

The matrix transpose can be done using the apostrophe key

C = B'
C =
2 7 2
2 7 1
3 9 11
4 8 12

For complex matrices use the command .' for transpose. The apostrophe gives the
complex conjugate transpose.. Note that if the matrix is not complex the two commands
are the same.

We can address any row or column in a matrix using the symbol (:).For example
R2=c(2,:)
R2 =
2 6 10
displays elements of the second column in C.

Multiplying matrices in MATLAB is also straightforward. Let us multiply B and C


D = B * C
D =
30 80 86
80 243 216
86 216 270

Note that the order matters

D = C * B

D =
57 53 91 88
53 51 77 72
91 77 211 216
88 72 216 224

The MATLAB operator .* is used when multiplying the corresponding elements of two
equal size matrices.

All matrices operations including summation, subtraction, division, and other operations
are performed in MATLAB in a direct and simple way. Suppose we have

A= [1 2 3;4 5 6;7 8 9];


A=
1 2 3
4 5 6
7 8 9
B=[3 5 2;5 2 8;3 6 9];
B=
3 5 2
5 2 8
3 6 9
The addition of the two matrices is

X=A+B
X=
4 7 5
9 7 14
10 14 18

and the subtraction is


Y=A-B
Y=
-2 -3 1
-1 3 -2
4 2 0
For addition and subtraction, matrices must be of the same dimension. For division, the \
/ symbols are used. The division A\B is equivalent to A-1B and A/B is equivalent to AB-
1
.

With a dot product we multiply the corresponding elements of two equally sized matrices
using the .* operator. For example

E = [1 2;3 4]
F = [2 3;4 5]
G = E .* F
E =
1 2
3 4

F =
2 3
4 5
G =
2 6
12 20

It is also possible to multiply any matrix by itself by raising it to a given power

E^3
ans =
37 54
81 118

In order to cube each element in the matrix, we use element-by-element cubing

E.^3
ans =
1 8
27 64

The inverse of a matrix can be computed with the inv command

X = inv(E)

X =
-2.0000 1.0000
1.5000 -0.5000
or its eigenvalues

eig(E)
ans =
-0.3723
5.3723

In MATLAB there is an important function named poly which is used to find the
coefficients of the characteristic polynomial of a matrix

pl = poly(E)
pl =
1.0000 -5.0000 -2.0000

Note that the eigenvalues of a matrix and the roots of its characteristic polynomial are the
same

roots(pl)
ans =
5.3723
-0.3723

Example 1.1
The linear system below is represented by the matrix equation Ax=B. It is required to
determine the vector x
4 - 2 - 10 x1 - 10
2 10 - 12 x 32
2
- 4 - 6 16 x3 16

In MATLAB, it will be the following statement

A=[4 -2 -10; 2 10 -12; -4 -6 16];


B=-10; 32; -16];
x=A\B
x=
2.0000
4.0000
1.0000

Example 1.2

Determine the inverse of matrix A using inv function

A=[4 -2 -10; 2 10 -12; -4 -6 16];


B=-10; 32; -16];
C=inv(A);
x=c*B
x=
2.0000
4.0000
1.0000

1.8 Utility Matrices


Utility matrices are practically useful in many cases of matrix operation. A few special
utility matrices are shown in Table 1.4.

Table 1.4 Special utility matrices


Matrix Description
Eye(m,n) Creates an m by n identity matrix
Zeros(m,n) Creates an m by n zeros matrix
Ones(m,n) Creates an m by n ones matrix

In order to compute the diagonal elements of any matrix we need to use the function diag.

Consider the matrix


A=eye(5,5);
diag(A)

ans =
1
1
1
1
1

1.9 Exporting to Excel Spreadsheet Files


MATLAB can transfer an output matrix to Microsoft Excel spreadsheet files. The
command xlswrite is used to export the matrix file from the workspace to any specified
location of the worksheet.
Example 1.3
In this example we show how to write numeric data to the default worksheet. We write a
vector of seven elements to MS Excel file testdata.xls. By default, the data will be
located in the cells A1 through G1
xlswrite('testdata', [12 7.98 -88.32 4.6 0 -.3 33])

Example 1.4
Mixed data numerics and text are written to the file named tempdata.xls
d = {'Time', 'Temp'; 12 98; 13 99; 14 97};
Now we call xlswrite, to specify the worksheet to write the data as labeled Temperatures
and a 4-by-2 matrix will be written
s = xlswrite('tempdata.xls', d, 'Temperatures', 'E1')
s=
1
shows that the write operation succeeded. Data will appear in the output file as
Time Temp
12 98
13 99
14 97

1.10 Long Command Lines


For long statements which cannot be typed in one line, we can use three periods, ,
followed by Enter. For example

x = sin(1) - sin(2) + sin(3) - sin(4) + sin(5) -...


sin(6) + sin(7) - sin(8) + sin(9) - sin(10)

x =
0.7744

If we want to suppress output to the screen, we need to add a semicolon after the
statement

r = 3 + 4;

1.11 Demos
A demo command is provided in MATLAB to provide the user with additional learning.
It can be executed either from the Command Window or the Pull-down menu. From the
menu we just click on Help, then select Examples and Demos.

1.12 Interrupting a Running Program

We can interrupt a running program simply by pressing the two keys Ctrl-c
simultaneously.

1.13 Saving and Reloading


In MATLAB, all variables used in the current session are automatically saved and can be
viewed in the Workspace. To view it, click on File in the toolbar and from the pull-down
menu select Show Workspace. Furthermore, the contents of the workspace can be
viewed in the Command Window by typing the command whos

whos
Name Size Bytes Class
ans 1x1 16 double array (complex)
run 1x1 8 double array
ld 1x1 8 double array
rd 1x1 8 double array

Grand total is four elements using 48 bytes

displays variables with their sizes in the current session.

The command who is used to display only the used variables.


who
Your variables are:
ans ld run xr

To save the current workspace from the File menu select Save Workspace as and write a
name for the file in this format filename.mat, then click on Save. The created file must
be located in MATLAB's search path. It can also be saved directly from the Command
Window by typing save filename command and variables will be saved. To save
workspace we type the command diary filename and all created variables and commands
are saved in our file from this point. If we want to save it as a text file we need to use the
command diary off. To load a file into the workspace, we need to type the load filename
command.

1.14 Getting Help in MATLAB


The Help system in MATLAB is a great feature. To see all the help categories and topics
simply type Help. To see all MATLABs elementary math functions type help elfun. For
example, when we need to learn about the function abs, we type in the Command
Window

help abs
ABS Absolute value.
ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is
the complex modulus (magnitude) of the elements of X.

When we forget or do not exactly remember the full name of a function, then we can use
the command lookfor. For example

lookfor sqrt
REALSQRT Real square root.
SQRT Square root.
SQRTM Matrix square root.
EML_FISQRT_HELPER Helper function for eml-fixedpoint square
root
vsqrtm.m: % function out = vsqrtm(mat)
REALSQRT Overloaded for distributed arrays
SQRT Overloaded for distributed arrays
SQRTM Matrix square root.
SQRTM Matrix square root.
SQRT Symbolic matrix element-wise square root.

In order to open a new window on the screen, we need to use helpwin command. To
display the help text file for any function of command we double click on the
subdirectory, then double click on the selected function or command. A direct way to get
help text is with using helpwin command followed by an argument.

Browser-based help provided in MATLAB can be used by clicking on Help, then


selecting Help Desk (HTML). The web browser will be launched where we can access
the information we need by typing the name of the function or clinking on the highlighted
link.

1.15 Printing
MATLAB provides the user with easy functions and commands to print. The steps
needed for popular operation systems are as follows.

Macintosh and Windows

Click on M-file or the plot, then select Print from the File menu and hit return.

Unix
For Unix workstation we need to enter the command print -
P<printername>. To save a plot, we need to enter the command print
plot.ps or use the command lpr -P plot.ps. For an HP workstation,
we would instead use the command lpr -d plot.ps. To print an M-file, use
the command lpr -P <name of m-file>.m. For an HP workstation, we
would instead use the command lpr -d plot.ps<name of m-file>.m.

1.16 MATLAB Commands List


The commands list shown in Table 1.5 contains some elementary MATLAB commands
which are very useful for future reference. We can use the help command to get
information on how to use them.
Table 1.5 MATLAB basic commands
Command Description
Abs Absolute value
eig To compute the eigenvalues
format Format change
function Function creation in M-file
imag Imaginary part
Impulse Impulse response of linear systems
inv Matrix inverse
length Vector length
linspace Returns a linearly spaced vector
log Natural logarithm, also log10: common logarithm
logspace Returns a logarithmically spaced vector
norm Vector norm
ones Create a vector or matrix with elements of ones
real Real part
roots To find the roots of a polynomial
size Gives the dimension of a vector or matrix
sqrt Square root
zeros Create a vector or matrix with elements of zeros

Exercises

1. Evaluate using MATLAB:


(a) (b) 224 (c) 5 104 + 2.5 102
2. Solve using MATLAB the following array operations:
(a) 1+ [2 3 1].
(b) 3 x [1 4 8] .
(c) [1 2 3] x [0 1 1].
(d) Square each element of the vector [2 3 1].

3. Evaluate manually the given expressions, then use MATLAB to check the
answers:
(a) 2 / 2 * 3 (b) 2 / 3 2 (c) (2 / 3) 2
(d) 2 + 3 * 4 4 (e) 2 2 * 3 / 4 + 3 (f) 2 (2 * 3) / (4 + 3)
(g) 2 * 3 + 4 (h) 2 3 2 (i) 4 2

4. Use MATLAB to evaluate the following expressions:


(a) 2 (b) (c) (d) 22 (e) 1/2
(f) 1/2
(g) Compute the cube root of the product of 2.3 and 4.5
(h) Compute the square of 2

5. We have two vectors a and b defined as:


a = [2 -1 5 0]; b=[3 2 -1 4];
Using MATLAB, find the value of vector c. Notice that you need first to evaluate
the
vector c by hand the vector c:
(a) c =a b; (b) 2 * a + a . ^ b; (c) c = b . / a;
(d) c = b . a; (e) c = a . ^ b; (f) c = b + a - 3; (g) c = 2 . ^ b+a (h) c =
2*b/3.*a

6. For matrix B, find the array which results from the operation [B; B']. Use
MATLAB to determine which number is in row 5, column 3 of the result:

7. For the same matrix B, use MATLAB to (a) find the largest and smallest element
in B and their indices and (b) sort each column in B to create a new matrix C.

8. Given the matrices:


, and ,

9. Find their (a) array product, (b) array right division (A divided by B), and (c) B
raised to the third power element by element.

10. Matrix operations:


Create the matrices A and B:
Calculate:

C = A+B; and E = A*B;


11. What is the matrix A created by the following MATLAB
commands?

>> x=(1:2:5)
>> A=[x,x.^2,x.^3]
12. The MATLAB library stores data files and helps the user by loading and
displaying them. Load the files handle and earth using load command. Now we
need to know about these two files. Play the handle file using sound command.
We now need to have a speaker. For the earth file we will use the image
command to show the contents. When we have finished with them we may try
loading chirp, gong, laughter, splat, and train. These are audio files and therefore
we must use a sound command.

13. Generate a magic matrix using MATLAB command magic(k) which will generate
a
square magic matrix of KxK elements. Use the sum command to verify that the
sum of all
elements in each row, column, and diagonal of the created matrix has the same
value.
Chapter 2

MATLAB Graphics
2.1 Graphics
Creating plots in MATLAB is an easy process. The matrix and vector outputs which can
be obtained from MATLAB offer more flexibility for plotting in attractable and readable
graphs. Suppose we want to plot a function that varies with time. We first make a time
vector and then compute the function at each time element of the given vector, as
described in the next example.

Example 2.1

In this example we will show how one can generate a MATLAB graphical output using
the provided tools and features. The following script file explains how to generate sine
and cosine functions and display their output plots.

t=linspace(0,2*pi,30); % linear spaced vector


x=2*cos(t); y=2*sin(t);
figure(1),subplot(121)
plot(t,x)
title('Sine wave') % gives the title of the plot
ylabel('Amplitude') % gives the identity of y axis
xlabel('Time samples') % gives the identity of x axis
subplot(122),plot(t,y)
title('Cosine wave')
xlabel('Time samples')
figure(2),plot(t,y,':',t,x,'-')
title('Sine and Cosine')
xlabel('Time samples')
ylabel('Amplitude')
legend('sin(t)','cos(t)')% displays the legend of plots
grid
Sine wave Cosine wave
1 1

0.8 0.8

0.6 0.6

0.4 0.4

0.2 0.2
Amplitude

0 0

-0.2 -0.2

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8

-1 -1
0 2 4 6 8 0 2 4 6 8
Time samples Time samples

Figure 2.1: Sine and cosine waveforms

As stated in the above script file the output should generate two different plots. The plot
shown on the left of Figure 2.1 displays the sine waveform for one period of time and that
on the right the cosine waveform for one period of time. The script file also explains how
to plot multiple functions in one graph using the subplot command.

Sine and Cosine


1
sin(t)
0.8 cos(t)

0.6

0.4

0.2
Amplitude

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
Time samples

Figure 2.2: Both sine and cosine functions in one graph

Figure 2.2 contains both the sine and cosine waveforms in a single graph. We have used
just some of the capabilities which MATLAB has. As can be seen, both y and x axes were
labeled and the background of the graph was gridded using the grid command. Because
we have two plots in one graph, the legend function was also used.

The syntax for plots includes the following optional symbols and colors (Table 2.1).
Table 2.1 Color specifications and line style options
Color Specification Line style option
Long name short name Style Symbol
White w Plus +
Black k Solid _
Green g Dash-dot -.
Cyan c Dotted :
Blue b Dashed --
Red r Circle o
Magenta m Point .
Yellow y Star *

2.2 Logarithmic Plots


In many science and engineering applications it is necessary to use Log scale plots. They
provide the means of presenting data over a wide range of values and also identify more
characteristics of the data. MATLAB commands for plotting different functions with
different styles are shown in the following table (2.2).

Table 2.2 Commands used for logarithmic plots


Command Definition
Semilogy(x,y) Plots y vs. x with a log (base 10) scale for y and linear scale for x
Semilogx(x,y) Plots y vs. x with a log (base 10) scale for x and linear scale for y
Loglog(x,y) Plots y vs. x with a log (base 10) scale for both axes.
Area Filled area plot
Comet Comet-like trajectory
feather Feather plot
ezpolar Easy to use polar coordinates plotter
ezplot Easy to use function plotter
fill To fill 2-D polygons

Example 2.2

Consider the function;


y= 2^{-0.2x+10} for 0.1 x 60,
which is required to generate different linear and log scale plots, as can be seen in the
following script file.
x=linspace(0.1,60,1000); %generates a vector of 1000 points between 0.1 and 60
y=2.^(-0.2*x+10);
subplot(221)
plot(x,y),grid
xlabel('x-Linear')
ylabel('y-Linear'
subplot(222)
semilogy(x,y) ,grid
xlabel('x-Linear')
ylabel('y-Log')
subplot(223)
semilogx(x,y),grid
xlabel('x-Log')
ylabel('y-Linear')
subplot(224)
loglog(x,y),grid
xlabel('x - Log')
ylabel('y - Log')

From the script file above we get four different plots, as shown in Figure 2.3. Note that in
the last figure we show how to use the subplot command for combining more graph plots
together in one universal graph.
4
1500 10

2
1000 10
y - Linear

y - Log

0
500 10

-2
0 10
0 20 40 60 0 20 40 60
x - Linear x - Linear
4
1500 10

2
1000 10
y - Linear

y - Log

0
500 10

-2
0 10
-2 0 2 -2 0 2
10 10 10 10 10 10
x - Log x - Log
Figure 2.3: Plots of the function y with linear, semilog, and loglog scales
2.3 Plots with Special Graphics
So far, all plots which have been introduced are of the line type where data points are
connected by lines. In some, practical representation of data is required for graphical
representation.

MATLAB is capable of generating such plots using special commands, as summarized in


Table 2.3.

Table 2.3 Different plot commands


Command Definition
Bar(x,y) Vertical Bar Plot
Barh(x,y) Horizontal Bar Plot
Staires(x,y) Stair Plot
Stem(x,y) Stem Plot

Example 2.3

Consider using the sales data from a computer company for its annual sales for a certain
period (1988 until 1994). With MATLAB, it is possible to plot these data in 2-D
different plot styles as shown in Figure 2.4. The script file is

% This file is to generate different graphical plots using above commands:


yr=88: 94; % time series for years 1988:1994
sle=[8 12 20 22 18 24 27]; % sales in each year
subplot(221),bar(yr,sle,'r')
xlabel('Year'),ylabel('Sales in Millions')
subplot(222),barh(yr,sle)
ylabel('Year'),xlabel('Sales in Millions')
subplot(223),stairs(yr,sle)
xlabel('Year'),ylabel('Sales in Millions')
subplot(224),stem(yr,sle,'r')
xlabel('Year'),ylabel('Sales in Millions')
Figure 2.4: Different plot styles

2.4 Pie Plots


Pie charts are important for visualizing the relative sizes of different but related
quantities. MATLAB can produce pie chart using command pie(x).

Example 2.4
Consider grades distribution of a class as

Grade A B C D E
Number of Students 11 18 26 9 5

MATLAB script file is:

% Generating Pie chart


grd=[11 18 26 9 5];
pie(grd);
title('Class Grade')

which gives the final pie chart in Figure 2.5 showing the distribution of class grades.
Class Grade
7% A
16%
B
C
13%
D
E

26%

38%

Figure 2.5: Pie plot

2.5 3-D Plots


It is possible with MATLAB to produce 3-D plots using the commands shown below.

Table 2.4 3-D plots


Command Definition
Pie3 3-D pie plot
Scatter3 3-D scattering type plot
Stem3 3-D stem plot
Contour3 3-D contour plot
Bar3 3-D bar plot

Figure 2.6 displays the different plotting formats for data used in example 2.4.
1-D Pie Plot 3-D Bar Plot
7%
16% 10
13%
5

26% 0
12
34
38% 56
7 3
1 2

3-D Pie Plot no offset 3-D Pie Plot with offset

42% 42%
10% 10%

19% 19%
29% 29%

Figure 2.6: Different pie and bar plots

Note that more elementary 3-D plots can be found by using the Help command.

2.6 Histograms
A histogram plot shows the distributions of data where the overall range of a given set of
data is divided into smaller subranges or bins and the histogram shows how many data
points are in each bin.

Example 2.5
Let us generate a random matrix measuring 60x60. The MATLAB script file is
y=randn(60); %generate 60x60 matrix of random data
y=y(1,:); %taking the first row to be our data subplot(121),
plot(y)
xlabel('data samples')
ylabel('Amplitude')
subplot(122)
hist(y)
3 12

2 10

Amplitude 1 8

0 6

-1 4

-2 2

-3 0
0 20 40 60 -4 -2 0 2 4
data samples

Figure 2.7: Random data and their histogram

The random data of the first row and its histogram is shown in Figure 2.7.

2.7 Advanced MATLAB Graphics


The high-level graphical routines available in MATLAB allow the creation of two- and
three-dimensional graphs. The reader can run the demos which come with MATLAB to
become familiar with the graphical tools. It is possible to access demos from the
Command Window. We click on Help and from the pull-down menu we select Demos,
then Visualization and finally 2-D Plots; several buttons will be displayed. In order to
examine the M-file we need to select the option Line. This will give us an idea of how to
create the graph and the required computer code.

2.7.1 2-D Graphics


The plot function is a MATLAB basic command function used to generate 2-D graphs. If
we type help plot in the command window additional information and a full definition
will be displayed.

Example 2.6

Consider the given function

x
f ( x)
, -2 x 2
1 x2
which we need to plot with the elements of its vector representation [1].
% MATLAB solution

for n=1:2:5
n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
plot(x,y,'r')
xlabel('x')
ylabel('y')
title('2-D Graph')
grid
pause(3)
end

Figure 2.8: 2-D graph

Notice that several curves can be displayed in sequence, separated by three seconds, with
the pause command. The final curve is shown in Figure 2.8.

Example 2.7

In this example, we will produce a unit circle graph of radius 1.


The script file is:

t = 0:pi/100:2*pi;
x = cos(t);
y = sin(t); plot(x,y)
Figure 2.9: Unit circle of radius 1

2.7.2 Using colors for graphs


In MATLAB several colors can be used for graphs and are represented as

w white
y yellow
r red
m magenta
g green
k black
b blue
c cyan

Example 2.8

A new function fill will be used in this example where we try to fill a well-known object

n = -6:6;
x = sin(n*pi/6);
y = cos(n*pi/6);
fill(x, y, 'c')
axis('square')
title('Graph of the n-gone')
text(-0.45,0,'Please turn off your computer?')
Three input arguments or parameters are adopted. Two arrays/vectors, x and y, are
selected and the third parameter is 'c' for the selected color. The new command text is
used to annotate a text. The first two inputs are used to specify the text location and the
third one is the added text. Figure 2.10 displays the generated graph of the filled object.

Figure 2.10: Unit circle of radius 1 using fill function

2.7.3 3-D graphics


Plotting 3-D graphs is an easy thing to do in MATLAB with the use of the built-in
functions. For plotting curves in space we can use the plot3 functions command. For
mesh surfaces we use the command function mesh and command surfaces surf. For
contour plots we use the contour command. To plot a special surface, the functions
sphere and cylinder can be used. To get help on 3-D plot from the Command Window
we type help graph3d.

Example 2.9

This example explains how to graph a sinc function,

[X,Y] = meshgrid(-8:.5:8);
K = sqrt(X.^2 + Y.^2) + eps;
Z = sin(K)./K;
mesh(X,Y,Z,'EdgeColor','blue')
Figure 2.11: Mesh plot of the sinc function

To create a transparent mesh we need to disable hidden lines by using the command
hidden off.

Example 2.10

Generating colored surface plots is similar to generating a mesh plot. The only difference
is that we color the rectangular faces of the surface using the colormap command.

surf(X,Y,Z)
colormap hsv
colorbar

Figure 2.12: Plot of colored sinc function


The following list shows the color maps used in MATLAB.

white - all white


hsv - hue-saturation-value
copper - linear copper-tone
gray - linear gray scale
bone - gray scale with tinge of blue
hot - black-red-yellow-white
pink - pastel shades of pink
colorcube - enhanced color-cube
lines - color map with the line colors
vga - Windows colormap for 16 colors
flag - alternating red, white, blue, and black
autumn - shades of red and yellow
prism - prism
jet - variant of HSV
cool - shades of cyan and magenta
summer - shades of green and yellow
spring - shades of magenta and yellow
winter - shades of blue and green

Example 2.11

Suppose we have the following space curve function

r(t) = t cos(t),
t sin(t), -20< t < 20,

The following script file [1] shows how to use the command function plot3 over a given time
interval
% Curve Function
t = -20*pi:pi/100:20*pi;
x = t.*cos(t);
y = t.*sin(t);
h = plot3(x,y,t);
set(h,'LineWidth',1.25)
title('Curve Function')
h = get(gca,'Title');
set(h,'FontSize',12)
xlabel('x')
h = get(gca,'xlabel');
set(h,'FontSize',12)
ylabel('y')
h = get(gca,'ylabel');
set(h,'FontSize',12)
zlabel('z')
h = get(gca,'zlabel');
set(h,'FontSize',12),grid
Note that the function plot3 was used with three inputs representing the three parameters
related to the coordinates of points on the plotted curve (Figure 2.13).

Figure 2.13: Curved functions

The mesh function is used to plot 3-D mesh surfaces where the function meshgrid
generates two-dimensional arrays used for 3-D plots.

One example of this function is when we want to plot a mesh surface in this form

x = [1 2 3];
y = [11 12 14];

Now we apply the meshgrid command to create two matrices

[xi, yi] = meshgrid(x,y)


xi =
1 2 3
1 2 3
1 2 3
yi =
11 11 11
12 12 12
14 14 14

Note that the matrices xi and yi contain replicated rows and columns of the arrays x and y
respectively.
2.7.4 Sphere and cylinder commands
For generating special surfaces in MATLAB some functions are used. We focus our
attention on the two most commonly used ones, sphere and cylinder.
We need to type the command sphere(n) in order to get a sphere centered at the origin.
If n is not specified, then the default valued n=20 is used. The center of the sphere can
be translated easily. The next example explains how to plot a unit sphere graph centered
at the coordinate points (2, -1, 1).

[x,y,z] = sphere(20);
surf(x+2, y-1, z+1)
title('Sphere')

Figure 2.14: Sphere plot

To plot spheres of arbitrary radii, we need to use the function sphere together with the
surf or mesh function. Figure 2.14 displays the obtained sphere plot with surf function.
The function cylinder is usually used when we need to plot the surface of revolution by
taking two optional input arguments or parameters: for example, the command
cylinder(r, n), where r is the parameter/vector defining the cylinder radius on the z-axis
and n is a scalar specifying the number of points used to define the cylinder's
circumference. Figure

Now, let us run this command

cylinder([1 0])
title('CONE')
Figure 2.15: Plot of cylinder

is a cone with unit diminution for both its base radius and its height.

It is possible to plot a graph of the surface and rotate the curve about the y-axis.
t = 0:pi/100:pi;
r = sin(t);
plot(r,t)
cylinder(r,15)
shading interp

3.5

2.5

1.5

0.5

0
0 0.2 0.4 0.6 0.8 1

Figure 2.16: Plot of r vs. t.


1

0.8

0.6

0.4

0.2

0
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1

Figure 2.17: Cylinder(r,15)

2.7.5 Animation

It is possible with MATLAB to make a sequence of graphs in motion or as a movie. To


generate movie graphs we need to use the graphics tools and commands provided in
MATLAB, including moviein and movi commands.

Example 2.12
To create a movie object, consider the following MATLAB file in which we try to run a
sequence of graphs in motion or movie.
m = moviein(5);
x = 0:pi/100:pi;
for i=1:5
h1_line = plot(x,sin(i*x));
set(h1_line,'LineWidth',1.5,'Color','m')
grid
title('Sine functions sin(kx), k = 1, 2, 3, 4, 5')
h = get(gca,'Title');
set(h,'FontSize',12)
xlabel('x')
k = num2str(i);
if i > 1
s = strcat('sin(',k,'x)');
else
s = 'sin(x)';
end
ylabel(s)
h = get(gca,'ylabel');
set(h,'FontSize',12)
m(:,i) = getframe;
pause(2)
end
movie(m)
Five frames will be replayed again at a different speed.

The command moviein tells MATLAB to create five frames. The consecutive frames
will be generated inside the loop for where the command getframe is to store movie in
the matrix m. The last command movie(m) is to tell MATLAB to start playing a movie
of the created and stored frame/s in the matrix m.

2.8 Printing Graphics


Printing graphics in MATLAB is an easy task. To print the current graph we need to click
on File, then from the pull-down menu we select Print. It is possible to get a graph
printed directly by using the Print command from the Command Window.

To print graphs to an M-file we need to use the built-in device drivers. Any graph can be
printed to an M-file using any of the following built-in device drivers:
-depsc Level 1 color Encapsulated PostScript
-deps2 Level 2 black and white Encapsulated PostScript
-depsc2 Level 2 color Encapsulated PostScript

If, for example, we want to print a graph to an M-file with level 2 color Encapsulated
PostScript, we need to execute this command: print depsc2 figure name. This
command can either be put inside the M-file or executed from the Command Window.

2.9 MATLAB Commands List


Table 2.5 contains a list of useful commands related to the topics presented in this
chapter. We can use the command help to get more information on any of these
commands.
Table 2.5 List of commands
Command Description
Abs To find the absolute value
Axis Set the scale of a plot
Bode To draw Bode plot
C2d Convert from continuous system to discrete system
clf Clear figure
figure To create a figure
grid Draw girded lines
gtext To add a text to a plot
hold To hold the current graph
imag Returns imaginary part
Impulse To give the impulse response of linear system
Legend To create graph legend
length Length of a vector
linspace To create a linearly spaced vector
log Natural logarithm
loglog To plot with log-log scale, also semilogx/semilogy
logspace Returns a logarithmically spaced vector
real Returns the real part
Stairs Stair step plot for discrete response
Tf Creation of transfer functions
title To add a title to a plot
xlabel/ylabel Adding labels to the axis of a plot
Chapter 3

Programming in MATLAB
This chapter will help users to learn the fundamental programming skills of MATLAB
language. Beginners will be able to write their computer codes for solving problems even
with limited knowledge of MATLAB language. Numerous examples are included to help
users quickly learn the basic tools and techniques of how to program in MATLAB.

Topics introduced in this chapter will include writing M-files, using relational and logical
operators, strings, inline functions, cell arrays, control flow, and MATLAB graphics.

3.1 The M-file


In MATLAB, a file written in a computer code is called an M-file. M-files are of two
types: script files and function files. The main difference between the two types is that the
function type takes input arguments and returns output arguments and the script type file
does not.

In order to create an M-file we click on File, then select New and from the pull-down
menu select M-File. A MATLAB Editor screen will appear where we can write our
code. For saving your code, from File select Save As and then we can chose a name for
your file and click on Save. and It is important saved it a MATLAB's search directory.
Note that if there are more than one file with duplicated names, the first occurred in the
search path will be executed. For opening existed m-file from the command window we
need to type filename then press Enter key and the file will be displayed.

3.1.1 Script file


Writing a script file is common practice in MATLAB and is useful for short codes which
do not need generalized forms.

Let us consider the following script file which generates a graph.

% Script file to generate a scaled sinusoidal function


t = pi/100:pi/100:10*pi;
y = sin(t)./t;
plot(t,y)
grid
The first line gives the title of the code and begins with the percentage sign %. We use
the percentage sign for comment and to improve readability of the code and it is ignored
by MATLAB. In the next two lines we create the arrays t and y. A semicolon following
the command is used to prevent the vector contents from being displayed on the screen.
Note that we use the dot operator ./ to perform the element by element division or what
is called component wise division of the two arrays. To create the graph of the sine
function we need to write the command plot. To add a grid to the output graph we use the
command grid.

0.8

0.6

0.4

0.2

-0.2

-0.4
0 5 10 15 20 25 30 35

Figure 3.1: Scaled sinusoidal function

3.1.2 Function Files

Programming using function styles is an advanced level of writing codes in MATLAB.


As can be seen, all MATLAB toolboxes have hundreds of built-in functions
implementing theoretical and applied engineering and mathematical algorithms. Let us
show by example how one can write a MATLAB code with the function file format.

Consider the following function which sorts in descending order.

function [b, j] = sortdesc(a)


% sorts vector a in descending order
% b is the sorted output array j is a parameter which holds
% a permutation used to obtain b
[b ,j] = sort(-a);
b = -b;
Note that the function sortdesc takes one input argument a and returns a sorted array b
and a permutation j to obtain b from a. The sort function is a built-in MATLAB function
which sorts numbers in ascending order.

Now let us test this function as

a=[4 6 -1 8];
[b,j]=sortdesc(a)

b=
8 6 4 -1
j=
4 2 1 3

Note that if we execute function sortdesc without output arguments we will lose the
permutation information

sortdesc(a)
ans =
20.0000 4.0000 0.1500 -10.0000

The output results will be assigned the default variable ans since there is no defined
output argument.

3.2 Inline Functions and the Feval Command


During the current MATLAB session only, it is useful to define a handy function. A
useful one is the inline command which is used for defining inline functions. For
example,

k = inline('sqrt(m.^2+n.^2)','m','n')
k=
Inline function:
k(m,f) = sqrt(m.^2+n.^2)

This function can be evaluated as

k(3,4)
ans =
5

and also works with arrays


M = [3 4;5 6]
M=
3 4
5 6

and
Z = zeros(2)
Z=
0 0
0 0
Then

D = k(M, Z)
D=
3 4
5 6

3.3 Logical Operators and Control Flow


MATLAB provides four devices for the command flow control:

_ the for loops


_ the while loops
_the break statements
_the continue statements
_ the if-else-end statements
_ the switch-case statements

3.3.1 Repeating with for Loops

The for loop we have the following syntax

for m = array
commands
end

All commands between the statements for and end will be executed for all values of the
array.
Example 3.1

In this example we want to obtain values of a cosine function at 20 evenly spaced points
t/10, for t = 0, .1, , 1 using for loop

for t=0:1:20
x(t+1) = cos(pi*t/20);
end
x
Columns 1 through 7
1.0000 0.9877 0.9511 0.8910 0.8090 0.7071 0.5878
Columns 8 through 14
0.4540 0.3090 0.1564 0.0000 -0.1564 -0.3090 -0.4540
Columns 15 through 21
-0.5878 -0.7071 -0.8090 -0.8910 -0.9511 -0.9877 -1.0000

Example 3.1 Matrices Addition

This is an example of for loops where we repeat the process of the program once for each
index value i.

function z=add(r,c)
% This function adds two matrices a and b
%
[r,c]=size(a);
[k,l]=size(b);
if r~=k | c~=l,
r='ERROR: matrices are not the same size';
return,
end
z=zeros(r,c);
for i=1:r,
for j=1:c,
z(i,j)=a(i,j)+b(i,j);
end
end
Example 3.2 Matrices Multiplication

function z=mult(a,b)
% produces a product of the matrices a and b
%
[r,c]=size(a);
[k,l]=size(b);
if c~=k,
z='ERROR: matrices are not compatible for multiplication',
return,
end,
z=zeros(r,l);
for i=1:r,
for j=1:l,
for e=1:c,
z(i,j)=z(i,j)+a(i,e)*b(e,j);
end
end
end

Example 3.4 Hilbert Matrix with for loops

We create the famous Hilbert matrix using for loops. Note this matrix can be nested and
has two levels of for loops

HM = zeros(7);
for r=1:7
for c=1:7
HM(r,c) = 1/(r+c-1);
end
end

HM

HM =

1.0000 0.5000 0.3333 0.2500 0.2000 0.1667 0.1429


0.5000 0.3333 0.2500 0.2000 0.1667 0.1429 0.1250
0.3333 0.2500 0.2000 0.1667 0.1429 0.1250 0.1111
0.2500 0.2000 0.1667 0.1429 0.1250 0.1111 0.1000
0.2000 0.1667 0.1429 0.1250 0.1111 0.1000 0.0909
0.1667 0.1429 0.1250 0.1111 0.1000 0.0909 0.0833
0.1429 0.1250 0.1111 0.1000 0.0909 0.0833 0.0769
We start by creating a 5x5 zero matrix to assign a space in the computer's memory and
also to reduce the number of loops used in MATLAB. Then we have to construct two for
loops to deal with the two-dimensionality of the matrix. Note that using for loops is only
recommended when other tools do not work.

Let us consider generating a 10x10 matrix M = [mrc], where mrc = sin(r)cos(c).


N=10;
M = zeros(N);
for r=1:N
for c=1:N
A(r,c) = sin(r)*cos(c);
end
end
However, in the same time we can solve it without using the for loops:
r = 1:10;
M = sin(r)'*cos(r);

Similarly to before we start creating a row vector k of integers 1, 2, , 10. In the second
line we multiply the two vectors sin(r)' and cos(r) to get matrix A. This is what is called
vectorization in MATLAB and is a technique to be used whenever possible.

3.3.2 While Loops


Usually, a while loop is used when the user does not know a priori the number of
repetitions in her/his code. The construction of a while loop has the following form:
while <condition>,
<program>,
end.
and the condition is a MATLAB function.

The while loop syntax is of this form

while expression
statements
end

Let us now try to solve a problem that requires the use of a while loop. We want to
divide the by two and the result is again divided by two until it is equal to or less
than 0.02. If it is necessary to know the largest quotient greater than 0.02, the while
loop is the right tool.
r = pi;
while r > 0.02
r = r/2;
end
r
r=
0.0123

Note that as long as the condition value is not zero, this program will execute
successfully.

Example 3.5 The bisection method

The algorithm of the bisection method used to solve nonlinear functions is discussed in
Chapter 5. Let us look at the use of the while loop now, however.

% Bisection
m = 0; fm = -Inf;
n = 3; fn = Inf;
while n-m > eps*n
x = (m+n)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fm)
a = x; fm = fx;
else
n = x; fn = fx;
end
end
x =
2.0946

3.3.4 Important Commands and Statements

Continue: is a statement used to pass control to the next iteration of the for or while
loop and skips remaining statements in the body of the loop.

Break: provides an early exit from a for or while loop.

Example 3.6

This program counts lines in a MATLAB code[1]:

snd = fopen('magic.m','r');
count = 0;
while ~feof(snd)
line = fgetl(snd);
if isempty(line) | strncmp(line,'%',1)
continue
end
count = count + 1;
end
disp(sprintf('%d lines',count));

3.3.4 Relations and Logical Operators

In MATLAB, the comparison of quantities or arrays needs one of the special operators
shown in Table 3.2.

Table 3.2 Special Operators


Special Operator Description
< Less than
<= Equal to or less than
> Greater than
>= Equal to or greater than
== Equal to
~= Not equal to

Note that the operator == is used to compare two given variables. It gives ones when the
two variables are equal and zeros otherwise. For example,

a = [1 1 3 4 1]
a=
11341
To compare a with 1

fin = (a == 1)
fin =
11001

Extracting entries equal to ones we use

b = a(fin)
b=
125

Instead of using logical operators, we can use the function find to obtain the same result

fin = find(a == 1)
fin =
125
3.3.5 Logical Operators
Logical operators are used in MATLAB programming. They are listed in Table 3.3.

Table 3.3 Logical Operators


Logical Operator Description
| And
& Or
~ Not

Let us show how to use these operators. Suppose that we have the inequality t 1or t<-
0.5 and need to select entries which satisfy it.

t = randn(1,5);
t=
0.5377 1.8339 -2.2588 0.8622 0.3188
is an array of random numbers that is normally distributed.

Using AND operator


ind = (t >= 1) | t < -0.5)
ind =
0 1 1 0 0

y = t(ind)
y=
1.8339 -2.2588

MATLAB has several additional functions which perform similarly to the logical
operators. They return one when the condition is satisfied and zero otherwise. Their
names usually begin with the prefix is. For example,

isempty(y)
ans =
0
because the array y is not empty.

isempty([ ])
ans =
1
because the argument is empty [ ].

Let us try using the isempty command through the following function.
function df = derp(c)
% df is the derivative of the algebraic polynomial represented by
% polynomial coefficients c stored in descending order.
m = length(c) - 1;
c = c(:)'; % to make sure c is a row vector.
df = c(1:n).*(m:-1:1); % to apply Power Rule.
h = find(df ~= 0);
if ~isempty(h)
df = df(h(1):end); % remove any leading zeros
else
df = 0;
end

3.3.6 The if-else-end Constructions


In MATLAB it is possible to use these constructions in a very constructive and simple
way.

if expression
commands
end
and is used with only one alternative.
For several alternatives the following construction is used

if expression1
commands (evaluated if true )
elseif expression 2
commands (evaluated if is true)
elseif
.
.
else commands (executed if all expressions are false)
end

In the next numerical examples we will show how to implement these constructions in
different scenarios.

Example 3.7

Your bank offers an interest rate of 7% when the amount in your account is less than
$4200 and 10% otherwise. Your current balance is $10000. The MATLAB script for
implementing this statement is:

bal = 10000 ;
if bal < 4200
rate = 0.07;
else
rate = 0.10;
end
newbal = bal + rate * bal;

and will give the instantaneous final new balance (newbal); it does not consider the
period of time you want to keep your money for.

Example 3.8

Suppose that the bank in the last example offers interest rates as follows

9% for balance amount (5000>=balance)


12% for (5000< balance <=10000)
15% for (balance>10000)

Now, we have $4900 and want to invest it for 10 years. Write a MATLAB code to
compute the following.
What is your final balance?
Plot the balance growth using the correct plotting format.

% MATLAB script file


bal = 4900; % starting balance
for i=1:10
if bal <= 5000
rate = 0.09;
elseif bal < 10000
rate = 0.12;
else
rate = 0.15;
end
bal = bal + rate * bal;
B(i)=bal;
format bank % gives we 4 digits format
end
figure,bar(B)
title('Balance for 10 years')
xlabel('Years'),ylabel('$')
Balance for 10 years
18000

16000

14000

12000

10000
$

8000

6000

4000

2000

0
1 2 3 4 5 6 7 8 9 10
Years

Figure 3.2: Balanced growth for 10 years

3.3.7 The Switch-Case Constructions

The syntax construction of the switch-case is

switch expression (string or scalar)


case 1 (executes if expression evaluated to value1)
commands
case 2 (executes if expression evaluated to value2)
commands
.
.
otherwise
statements
end

Switch command compares inputs with each case value and then executes once a match
is found.

Example 3.10

In this example we display a set of probabilities associated with some conditions.


Suppose that we generate a random integer number y from the set {1, 2, 3, , 10}. The
probability is 20% if p=1 or 2 and will be displayed on the computer screen. A
probability message of 30% will be displayed if y=3,4 or 5; otherwise a probability of
50% will be displayed.
y = ceil(10*rand); % to generate random integers in {1, . , 10}, ceil rounds towards +
infinity
switch x
case {1,2}
disp('P = 20%');
case {3,4,5}
disp('P = 30%'); % to display string
otherwise
disp('P = 50%');
end

When we tried to run the above script file five times we got these results
P = 20%
P = 30%
P = 50%
P = 30%
P = 50%

3.4 Strings
Strings are an array of characters replaced in as their elements. Each character in the
array is represented by its ASCII value.
Example 3.11

mis = 'I am traveling to Canada this summer.'


mis =
I am traveling to Canada this summer.

The ASCII representation can be obtained with the function double

mis1 = double(mis)
mis1 =
Columns 1 through 15
73 32 97 109 32 116 114 97 118 101 108 105 110 103 32

Columns 16 through 30
116 111 32 67 97 110 97 100 97 32 116 104 105 115 32

Columns 31 through 37
115 117 109 109 101 114 46

To convert mis1 to its character form use the function char

str2 = char(mis1)
str2 =
I am traveling to Canada this summer.

If we want to compare the two strings for equality we can use the function strcmp

iseq = strcmp(mis, str2)


iseq =
1

To concatenate two strings

strcat(mis,str2)
ans =
I am traveling to Canada this summer. I am traveling to Canada this summer.

3.5 Cell Arrays


Another factor which makes MATLAB a powerful tool is its data types cell arrays and
structures. Cell indexing and content indexing are two techniques used to generate cell
array. Next we try to reveal the differences between these two techniques.

3.5.1 Cell Indexing


Suppose we want to save the string Ahmed Hussain' and his SID 313-12-5678 (without
dashes) in the cell array.

A(1,1) = {'Ahmed Hussain'};

A(1,2) = {[3 1 3 1 2 5 6 7 8]};

3.5.2 Indexing

B{1,1} = 'Ahmed Hussain';


B{1,2} = [3 1 3 1 2 5 6 7 8];

The condensed form of A is


A
A=
'Ahmed Hussain' [1x9 double]

For the full form we use the function celldisp

celldisp(A)
A{1} =
Ahmed Hussain
A{2} =
313125678

Empty matrix operator [ ] can be use for cell deletion

B(1) = []
B=
[1x9 double]

removes cell B(1, 1) from array B.

To create a new cell of arrays


C = {A B}
C=
{1x2 cell} {1x1 cell}

celldisp(C)
C{1}{1} =
Ahmed Hussain
C{1}{2} =
313125678
C{2}{1} =
313125678

3.6 Rounding to Integers


In the last sections we encountered some MATLAB functions such as round and ceil
which we used in rounding real numbers to integers. There are additional functions which
can be used and they are shown in Table 3.4.

Table 3.4 Special Operators


Function Description
Round To round towards nearest integer
Ceil To round towards plus infinity
Floor To round towards minus infinity
Fix To round towards zero

The following example illustrates the use of these operators.

T = randn(5)
T=
0.5377 -1.3077 -1.3499 -0.2050 0.6715
1.8339 -0.4336 3.0349 -0.1241 -1.2075
-2.2588 0.3426 0.7254 1.4897 0.7172
0.8622 3.5784 -0.0631 1.4090 1.6302
0.3188 2.7694 0.7147 1.4172 0.4889

A = floor(T)
A=
0 -2 -2 -1 0
1 -1 3 -1 -2
-3 0 0 1 0
0 3 -1 1 1
0 2 0 1 0
B = ceil(T)
B=
1 -1 -1 0 1
2 0 4 0 -1
-2 1 1 2 1
1 4 0 2 2
1 3 1 2 1

C = fix(T)
C=
0 -1 -1 0 0
1 0 3 0 -1
-2 0 0 1 0
0 3 0 1 1
0 2 0 1 0
D = round(T)
D=
0 -1 -1 0 0
1 0 3 0 -1
-2 0 0 1 0
0 3 0 1 1
0 2 0 1 0

Problems

1. Use the for end commands to calculate the sum:

2. The two functions F(t) and G(t) shown as


F(t) =3 t2 + 2 t - 0.5
G(t) = 2 t cos(t)
are functions of the variable t which varies from zero to 10 with an incremental step of
0.5. Using these functions do the following:
-write a MATLAB script file that describes them
-plot them in one graph using all possible graph features provided by MATLAB
including colors, line style, grid, legend, title, xlabel, ylabel, etc.

3. Use MATLAB to compute the arithmetical mean shown in the equation below. First
create the vector g of a random real number with n=20.
1 n
mean( g ) gk
n k 1
PART II

Analytical and Numerical Methods


Using MATLAB
Chapter 4

Linear Algebra Aspects


and Solution Methods
for Systems of Linear Equations

4.1 Introduction
As mentioned in the first chapter all mathematical operations and algorithms can be
simulated in MATLAB. A distinct feature of MATLAB is its simplicity in terms of
performing computations using vectors and matrices. This chapter will explain how
matrices and vectors are used in MATLAB, including solving systems of linear
equations, determinants, inverse of an invertible square matrix, linear transformation,
eigenvalue problems and representing vectors in n-dimensional space. Linear numerical
methods such as regression, interpolation, roots of non-linear equations, special
functions, different types of series, curve fitting, message coding, and computer graphics
will be presented with some examples and applications.

4.2 Vectors and Matrices in MATLAB


We will demonstrate in this section the creation and manipulation of matrices and vectors
in MATLAB.

Let us create a row vector

x = [2 3 4]
x =
2 3 4

and column vectors

y = [2;3;4]
y =
2
3
4

For transpose and conjugate transpose we use conjugate transpose ' and quote operator
,' respectively. Let us create a vector x + i*y' and perform the following operations
(x+i*y')'
ans =
2.0000 - 2.0000i
3.0000 - 3.0000i
4.0000 - 4.0000i
while

(x+i*y').'
ans =
2.0000 + 2.0000i
3.0000 + 3.0000i
4.0000 + 4.0000i

To determine the length of a vector, we can use the command length

length(x)
ans =
3
An example of using dot operator. is

x.*x
ans =
4 9 16

We can obtain the same result using power operator ^

x.^2
ans =
4 9 16

To obtain wise division we use the backslash and dot operators .\ together,

x.\y'
ans =
1 1 1

To perform the dot product and the outer product


dotprod = x*y
dotprod =
29

outprod = x*y'
outprod =
4 6 8
6 9 12
8 12 16
In the case of a three-dimensional vector, we use the command cross. The cross-product
of the two vectors a and b is
a = [1 2 3]
b = [-2 1 2];
cp = cross(a,b)
cp =
1 -8 5
Now we need to deal with matriX operations such as addition, subtraction, and scalar
multiplication.

Let us create a 3x3 matrix


A = [1 2 3;4 5 6;7 8 10]
A =
1 2 3
4 5 6
7 8 10

Note that we used a semicolon operator ; to separate matrix rows.

We can extract submatrix B from A with columns 1 and 2 and rows 1 and 3
B = A([1 3], [1 2])
B =
1 2
7 8

We can interchange rows 1 and 3 of matrix A


C = A([3 2 1],:)
C =
7 8 10
4 5 6
1 2 3

Note that the colon operator : is used when we want all rows or all columns.

To transform a matrix into a vector we use


A(:)
ans =
1
4
7
2
5
8
3
6
10
The empty vector operator [ ] is used for deleting a row or column in a matrix

A(:, 2) = []
A =
1 3
4 6
7 10

To insert a row or a column

A = [A(:,1) [2 5 8]' A(:,2)]


A =
1 2 3
4 5 6
7 8 10

Note that the original matrix A is restored.

It is possible with MATLAB to extract entries to satisfy an imposed condition. Now let
us extract all entries greater than one in matrix A.

A = [-1 2 3;0 5 1]
A =
-1 2 3
0 5 1

A > 1
ans =
0 1 1
0 1 0
returns ones on the locations of entries with values greater than one.

To extract the entries

A(A > 1)
ans =
2
5
3
The dot operator . can be used as

A = [1 2 3; 3 2 1] ;
A.*A
ans =
1 4 9
9 4 1
computes the element-by-element product of A with A.
The command diag can be used for different purposes. We can create a diagonal matrix
using the elements of vector d as the diagonal entries

d = [1 2 3];
D = diag(d)
D =
1 0 0
0 2 0
0 0 3

Furthermore, the diag command can be used to obtain the diagonal of a matrix

d = diag(D)
d =
1
2
3

4.3 Solving Systems of Linear Equations


We start with the graphical solution method as the basic tool used for a small system
order n3. Suppose we have the following system

a11 x1 a12 x 2 b1
a 21 x1 a 22 x2 b2

The solution of the system is obtained at x1=x2. To find their solution graphically, we
need to solve both equations for x2

a b
x 2 11 x1 1 x 2 (slope)x1 intercept
a12 a12
a b
x 2 21 x1 2
a 22 a 22

Now we can plot both equations in terms of x1. The system has a solution if they intersect
and the intersection coordinates are the solution of the system x1 and x2.

Example 4.1

Consider the following linear system:


2x1 + 2 x2=18
-x1 + 2 x2=2

We want to solve the system using the graphical method with MATLAB.

x=0:.1:8;
y1=9-x;
y2=1+.5*x;
y3=(abs(y1-y2));
I=y3/min(y3);
ind=find(I==1);
x1=x(ind)
x2=y2(ind)
plot(x,y1,x,y2)
xlabel('x1'),ylabel('x2')
grid
x1 =
5.3000
x2 =
3.6500
Matlab solution for Hw-1 Problem-1
9

6
x2

1
0 1 2 3 4 5 6 7 8
x1

Figure 4.1: Graphical solution to.linear system of two equations

The two plots of the two equations are shown in Figure 4.1. The solution of the system is
actually the values of x1 and x2 at the interception points x1=5.3 and x2=3.6.

There are many tools in MATLAB for solving systems of linear equations. In general,
suppose we have a linear system Ax = b. The matrix A is an m-by-n matrix and the
vector b is an m-dimensional column vector. We can use the left division \ to solve this
system.
a) Case m = n

For this case we calculate the exact solution. In MATLAB we define the matrix and the
column vector as

Y = [1 2 3;4 5 6;7 8 10]


Y =
1 2 3
4 5 6
7 8 10
z = ones(3,1);

The known variables or the solution of the linear system equations can be obtained using
the left slash division

m = Y\z
m =
-1.0000
1.0000
0.0000

To verify our solution we compute the residuals

rez = z - Y*m
rez =
1.0e-015 *
0.1110
0.6661
0.2220

The residuals are very small and came from the rounding-off.

b) Case m > n

This system is called the over-determined system and is consistent in most cases. The
solution of this system using left division \ is the least square solution,

Let
Y = [2 1; 1 10; 1 2];
z = ones(3,1);
m = Y\z
m =
0.5849
0.0491
Residual values are shown in the following vector

rez = z - Y*z
rez =
-0.1208
-0.0755
0.3170

c) Case m < n

In this case the number of unknown variables exceeds the number of equations and this
system is defined as an under-determined linear system and its solution is consistent.

In MATLAB

Y = [1 2 3; 4 5 6];
z = ones(2,1);
m = A\b
m =
-0.5000
0
0.5000

4. 4 Special Functions and Applications


There are many built-in functions in MATLAB which allow users to use them directly.
One function is the rref which can be used to solve many systems and equations in linear
algebra. We will discuss this function and its applications such as solving systems of
linear equations and finding rank of a matrix.

The function rref returns a reduced row echelon form of the matrix

R = rref(A)
or
[R, pivot] = rref(A)

where pivot is a parameter used to hold the indices of the pivot columns.

Let us create a linear system Ax=b with,

A = magic(4);
b = ones(4,1);
To obtain the solution of the linear system Ax = b, the augmented matrix should be
transformed to the reduced echelon form. The solution of the system is stored in the last
column.

[x, pivot] = rref([A b])


x =
1.0000 0 0 1.0000 0.0588
0 1.0000 0 3.0000 0.1176
0 1.0000 -3.0000 -0.0588
0 0 0 0

pivot =
1 2 3

x = x(:,5)
x =
0.0588
0.1176
-0.0588
0

The errors or residuals are

b - A*x
ans =
0
0
0
0

To find the rank of the matrix A from the parameter pivot

length(pivot)
ans =
3
and the matrix A has a rank of 3.

4.5 Inverse of Matrix


In MATLAB, we can use the function inv to compute the inverse of any invertible square
matrix.

Let us create the following square matrix A


A = [2 3 4;5 6 7;8 9 2]
A =
2 3 4
5 6 7
8 9 2

The inverse matrix A-1 can be obtained using the inv command
E = inv(A)
E =
-2.1250 1.2500 -0.1250
1.9167 -1.1667 0.2500
-0.1250 0.2500 -0.1250

We can verify the above using the property A*A-1 = I and A-1*A = I,

A*E
ans =
1.0000 0.0000 -0.0000
0 1.0000 -0.0000
0 0.0000 1.0000
Similarly

E*A
ans =

1.0000 0 0
0 1.0000 -0.0000
0 0 1.0000

Pascal matrix: this matrix has several interesting properties and is defined in MATLAB
as pascal

A = pascal(4)
A =
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20

The matrix inverse A-1 is

B = inv(A)
B =
4.0000 -6.0000 4.0000 -1.0000
-6.0000 14.0000 -11.0000 3.0000
4.0000 -11.0000 10.0000 -3.0000
-1.0000 3.0000 -3.0000 1.0000
The Cholesky triangle or upper triangular matrix of A is
C = chol(A)
C =
1 1 1 1
0 1 2 3
0 0 1 3
0 0 0 1

Note that the binomial coefficients are in the upper triangular part. To verify that we use
A = C'*C
ans =

1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20

We can also compute the inverse of a matrix using the function rref introduced earlier.
We can use the above Pascal matrix A.

Let
A = pascal(4);
D = rref([A eye(size(A))]);
D = D(:, 5:8)
D =
4 -6 4 -1
-6 14 -11 3
4 -11 10 -3
-1 3 -3 1

Now we can verify it using this property A *D=D*A=I


A*D
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
and

D*A
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

4.6 Determinants
Many linear algebra applications require prior knowledge of the determinant of the
system matrix. We will examine some of these applications through examples. Now let
us identify the MATLAB built-in function det used to compute determinants.

Let us create the following square magic

A = magic(3);

The determinant of A, denoted by |A|, is

det(A)
ans =
-360

We know that for a matrix A to be invertible, it must be square and its determinant not
equal to zero. This is one application in which we must know in advance the matrix
determinant in order to choose the appropriate solution method.

Cofactor expansion: is a method for computing determinants. The determinant can be


derived by performing the cofactor expansion along any row or column of the matrix.

Let A be a square matrix of order n, so the determinant of A is given by


n
(a) det( A) | A | aij Cij ai1Ci1 ai 2Ci 2 ainCin
j 1
which is the cofactor expansion along the i-th row, i=1, 2,, n and
n
(b) det( A) | A | aij Cij a1 j C1 j a2 j C2 j anj Cnj
i 1

is the cofactor expansion along the j-th column, j=1, 2,, n

The implementation of this method is shown in the following MATLAB function ck =


cofactor (A, k, l) [3],

function ck = cofactor(A,k,l)
% ck: is the cofactors for matrix A.

[m,n]=size(A);
if m ~= n
error('Matrix must be square')
end
B = A([1:k-1,k+1:n],[1:l-1,l+1:n]);
ck=(-1)^(k+l)*det(B);
The following function d=youdet(A) can also compute the det of a matrix using the
cofactor expansion method [3].

function d=youdet(A)
% To compute the determinant of matrix A.
[m,n]=size(A);
if m ~= n
error('Matrix must be square')
end
a = A(1,:);
c = [];
for l=1:n
c1l = cofactor(A,1,l);
c = [c;c1l];
end
d = a*c;

The adjoint matrix is an important matrix used in solving systems of linear equations. We
can use the MATLAB adj(A) to compute the adjoint matrix.

function D=adj(A)

% To compute adjoint matrix D of matrix A.


[m,n]=size(A);
if m ~= n
error('Matrix is not square')
end
D=[];
for k=1:n
for l=1:n
D=[D;cofactor(A,k,l)];
end
end
D = reshape(D,n,n);

We can use the adjoint matrix along with the determinant to solve for the inverse matrix

A-1 = adj(A)/det(A)

4.7 Left-Division Method


MATLAB provides the left-division method for solving the equation set Ax=b and it is
based on Gauss elimination. It is also works in some cases where the number of
unknowns does not equal the number of equations. However, we will focus on problems
in which the number of equations equals the number of unknowns. If the number of
equations and the number of unknowns are equal and lAl 0, then the system has a
unique solution.

Example 4.2

Find the solution of the following system using the left-division method.

3x 2y 9z 65
9 x 5 y 2 z 16
6 x 7 y 3z 5

The coefficient matrix is

3 2 - 9
A - 9 - 5 2
6 7 3

To check the singularity of the matrix, compute the determinant first

A = [3 2 9; -9 -5 2; 6 7 3];
det(A)
ans =
288

The determinant is not equal to zero and therefore the system has a unique solution

A = [3 2 9; -9 -5 2; 6 7 3];
B=[-65;16;5];
A\b
Ans=
2
-4
7
Therefore the system solution is: x=2, y=-4, z=7.

To check whether Ax gives the vector b,

A*ans
ans=
-65
16
5
It is equal to vector b and therefore the answer is correct.

4.8 Gauss Elimination Method


The Gauss elimination method is a procedure for solving systems of linear equations. It is
manipulated to be in either upper or lower triangular form and then solved with back
substitution.

Example 4.3

Use the Gauss elimination method to solve the three unknowns of the following set linear
equations:

3x 2y 9z 65
9 x 5 y 2 z 16
6 x 7 y 3z 5

Also, write a MATLAB script file for the solution, showing the Gauss elimination
method.

The augmented matrix is

3 2 -9 - 65
- 9 - 5 2 16

6 7 3 5

If we apply the Gauss elimination method in either the upper or the lower triangular form,
we will get the following answer regarding the unknowns:

x=2
y=-4
z=7

To solve the system with MATLAB, we need to use the following Gauss MATLAB
function [3].

function [ x ] = Gauss(a,b)
% solving system of linear equations with Gauss Elimination
% a: matrix with coefficients
% b: column victor
% X: known variables
ab=[a,b];
[R,C]=size(ab);
for j=1:R-1
for i=j+1:R
ab(i,j:C)=ab(i,j)/ab(j,j)*ab(j,j:C);
end
end
x=zeros(R,1);
x(R)=zeros(R,1);
for i=R-1:-1:1
x(i)=(ab(i,C)-ab(i,i+1:R)*x(i+1:R)/ab(i,i);
end
end

To get the solution we need to inter the inputs as:

a=[3 2 -9;-9 -5 2;6 7 3];


b=[-65 16 5];
b=b';
x=Gauss(a,b)
x =
2
-4
7
as the solution for the values of the unknown system parameters.

4.9 LU Decomposition Method


LU factorization refers to the factorization of a square matrix A, with proper row and/or
column orderings or permutations, into two factors, a lower triangular matrix L and an
upper triangular matrix U.

The LU decomposition method is a method for solving a system of linear equations


[A][x]=[b]. In this method the matrix of coefficients [A] is decomposed or factored into a
product of two matrices [L] and [U]:

[A]=[L][U]
where [L] is the lower triangular matrix and [U] is the upper triangular matrix.
In the lower triangular matrix all elements above the diagonal are zero, in the upper
triangular matrix, all the elements below the diagonal are zero. For example, for a 3-by-3
matrix A, its LU decomposition looks like this:

a11 a12 a13 l11 0 0 u11 u12 u13


a a 23 l 21 l 22 0 0 u u 23
21 a 22 22

a31 a32 a33 l 31 l 32 l33 0 0 u 33


In MATLAB, there is a built-in function, lu, which performs this method. The function is
written as [L,U]=lu(a),
which provides outputs of L and U matrices to solve the unknowns.
Example 4.4

The following DC electrical circuit has three current loops, I1, I2, and I3. The mesh
equations are also provided.

The matrix of the linear system is

20 4 10 I1 30
4 18 11 I 18
2
10 11 30 I 3 20

Solve the system using the following methods:


a- Gauss elimination
b- Cramer's rule
c- Gauss-Seidal method
d- LU decomposition

%Example 4.4
clear all
A=[20 -4 -10;-4 18 -11;-10 -11 30];
b=[30;-18;20];
A1=A;A1(:,1)=b;
A2=A;A2(:,2)=b;
A3=A;A3(:,3)=b;
D=det(A);D1=det(A1);D2=det(A2);D3=det(A3);
X(1)=D1/D;X(2)=D2/D;X(3)=D2/D;

x'=
2.4732
0.5939
1.7088
b)
clear all
A=[20 -4 -10;-4 18 -11;-10 -11 30];
b=[30-18 20];
x=Gauss(A,b)
x'=
2.4732
0.5939
1.7088

c)
d)

clear all
A=[20 -4 -10;-4 18 -11;-10 -11 30];
b=[30;-18;20];
A1=A;A1(:,1)=b;
A2=A;A2(:,2)=b;
A3=A;A3(:,3)=b;
D=det(A);D1=det(A1);D2=det(A2);D3=det(A3);
X(1)=D1/D;X(2)=D2/D;X(3)=D2/D;
x';

[L,U]=lu(A);
z=L\b;
x=U\z;
x
x=

2.4732
0.5939
1.7088

4.10 Vectors
The Euclidean norm known as the 2-norm of a vector can be computed using the
MATLAB norm function.

Let
a = -2:2
a =
-2 -1 0 1 2

The 2-norm is

twon = norm(a)
twon =
3.1623

To compute the angle between two equal size vectors we need to use,
= arccos(a.b/||a|| ||b||),
where ||a|| is the norm of vector a, a.b stands for the dot product of a and b and arccos is
the inverse cosine function.

a = -2:2;
b = (1:5)';
Then
angle = acos((a*b)/(norm(a)*norm(b)))
angle =
1.1303

4.11 Real Vector Spaces


In this part of the chapter, we will introduce and discuss the real vector spaces including
vectors linear span and the transition matrices.

4.11.1 Linear Span


The linear span of vectors in a vector space is a very important concept in linear algebra.
For a given vector we can determine with MATLAB whether it is in the span of a set of
vectors or not. The MATLAB function span can be used in this case and returns an
output message displayed on the screen indicating whether the vector is in the span or not
[3].
function span(v,varargin)
% Test if vector v is in the span of a set of vectors.
A = [];
n = length(varargin); % variable number of vectors for the span
for i=1:n
u = varargin{i};
u = u';
A = [A u(:)];
end
v = v';
v = v(:);
if rank(A) == rank([A v])
disp(' Vector is in the span.')
else
disp(' Vector is not in the span.')
end

Note that the linear system Ax = b will possess a solution with this condition only:
rank(A)=rank( [A b] ).

Let us now test the function span with matrices.


e = ones(3);
A = pascal(3);
B = rand(3);
span(e, A, B)
The vector is not in the span.
Example 4.5

The following matrices


T = [1 2;3 4];
S = [0 1;1 0];

are the ordered bases of two vector spaces. We can use the above transmit function to
find the transition matrix

E = transmat(T, S)
E =
3 4
1 2

4.12 Eigenvalue Problem


The eigenvalues and eigenvectors are important for finding solutions for homogeneous
systems. In MATLAB we can use the eig function to find eigenvalues and eigenvectors.

[V, D] = eig(A)

The two outputs V and D are matrices of the same size as matrix A. The eigenvectors are
stored in columns of matrix V where eigenvalues are stored in the diagonal entries of
matrix D.

A = pascal(4);
[V, D] = eig(A)
V =
0.3087 -0.7873 0.5304 0.0602
-0.7231 0.1632 0.6403 0.2012
0.5946 0.5321 0.3918 0.4581
-0.1684 -0.2654 -0.3939 0.8638
D =
0.0380 0 0 0
0 0.4538 0 0
0 0 2.2034 0
0 0 0 26.3047

4.13 Coding and Decoding


Coding and decoding are an important subject in communication information systems.
We will now examine some basic tools of linear algebra for the coding and decoding of
messages. In MATLAB, we use the double function where a message is represented as a
string and then converted to a sequence of positive integers. The decoding of the message
is the inverse process. The MATLAB functions code and decode perform coding and
decoding respectively [3].

function B=code(s, A)

% s: coded string vector using a nonsingular matrix A.


% B: stored coded message vector

p = length(s);
[n,n] = size(A);
b = double(s);
r = rem(p,n);
if r ~= 0
b = [b zeros(1,n-r)]';
end
b = reshape(b,n,length(b)/n);
B = A*b;
B = B(:)';

function s=dcode(B, A)
[n,n]=size(A);
p = length(B);
B = reshape(B,n,p/n);
d = A\B;
s = char(d(:)');

The coded message is


s='MATLAB is fun';

Now let us use the Pascal matrix as a coding matrix


A=pascal(4);

To code the message s


B=code(s,A)
B=
Columns 1 through 7
398 1051 2144 3785 332 809 1633
Columns 8 through 14
2909 366 953 1993 3603 110 110
Columns 15 through 16
110 110
For decoding this message we use
dcode(B,A)
ans=
MATLAB is fun
4.15 Summary List of Special Characters and MATLAB
Functions
For the reader's convenience we include in the following tables lists of the MATLAB
functions and special characters used in this chapter and the rest of the book.

Table 4.1 MATLAB functions and their description


Function Function Description
axis To control axis scaling
eye Identity matrix
chol Cholesky factorization
det Determinant
cross Cross-product
magic To create a magic square matrix
eig Eigenvalues and eigenvectors
diag To obtain the diagonal elements of a matrix
fill To filled 2-D polygons
fliplr To flip matrix in left/right direction
fix Rounds towards zero
hilb Hilbert matrix
hadamard Hadamard matrix
inv Creates matrix inverse
hold To hold current graph
linspace Returns linearly spaced vector
length Returns vector length
norm Matrix or vector norm
logical Convert numerical values to logical values
num2str To convert numbers to strings
max To find the largest component
min To find the smallest component
null To create a null space
pascal To create a Pascal matrix
num2cell To convert numeric array into cell array
plot Linear plot
polyval Evaluate polynomial
poly To convert roots to polynomial
randn To get normally distributed random numbers
roots To compute polynomial roots
rand To get uniformly distributed random numbers
rem Remainder after division
sort Sort in ascending order
size Size of matrix
zeros Zero array
Table 4.2 Special characters in MATLAB
Special Characters
' Conjugated transpose
. Dot operator
* Times
.' Transpose
[] Empty vector operator
^ Power operator
= Assignment
: Colon operator
\ Backslash or left division
== Equality
i, j Imaginary unit
/ Right division
~= Logical not equal
~ Logical not
{} Cell
& Logical and
| Logical or

Problems

1.Create a row vector of length N=20 whose components are all equal to two without
entering the number two more than once.

2. Consider the given row vector a = [5 6 7 8 9]. Create a column vector b with the same
components but reversed order.

3. The MATLAB built-in function sort(a) is used for sorting components in ascending
order. Now we are required to sort vector a in descending order.

4. Without using function max (min), find the smallest and largest element or entry of a
given vector.

5. Create a row vector of random integers uniformly distributed in the interval (2, 10)
using function rand.
Hint: function fix might be helpful.

6. The matrix A is a square matrix. Create a matrix B whose entries are the same as those
of A except that the main diagonals are ones.
7. We have matrices A and B which are square and invertible and a column vector b and
all have the same number of rows. We want to solve the linear system equation ABx = b
using backslash \. and without conducting the matrices product A*B.

8. Determine whether the linear equation Ax = b has a unique solution.


A = ones(3, 2); b = [1; 2; 3];

9. Compare the computational complexity of two methods to solve linear system Ax = b


where A is a square matrix. One method should use the backslash operator \ and the other
the rref function.
Hint: use the flops function to compare the two methods.

10. Compute the rank of the given matrices using the MATLAB rref function
(a) C = magic(4)
(b) C = magic(5)

View publication stats

Das könnte Ihnen auch gefallen