Saturday 3 November 2012

2.2 X-Y PLOTS AND ANNOTATIONS

2.2 X-Y PLOTS AND ANNOTATIONS


The plot command generates a linear x-y plot. There are three variations of the
plot command.
(a) plot(x)
(b) plot(x, y)
(c) plot(x1, y1, x2, y2, x3, y3, ..., xn, yn)
If x is a vector, the command
plot(x)
will produce a linear plot of the elements in the vector x as a function of the
index of the elements in x. MATLAB will connect the points by straight lines.
If x is a matrix, each column will be plotted as a separate curve on the same
graph. For example, if
x = [ 0 3.7 6.1 6.4 5.8 3.9 ];
then, plot(x) results in the graph shown in Figure 2.1.
If x and y are vectors of the same length, then the command
plot(x, y)
plots the elements of x (x-axis) versus the elements of y (y-axis). For example,
the MATLAB commands
t = 0:0.5:4;
y = 6*exp(-2*t);
plot(t,y)
will plot the function y(t) = 6e−2t at the following times: 0, 0.5, 1.0, …, 4 .
The plot is shown in Figure 2.2.
To plot multiple curves on a single graph, one can use the plot command
with multiple arguments, such as
plot(x1, y1, x2, y2, x3, y3, ..., xn, yn)
The variables x1, y1, x2, y2, etc., are pairs of vector. Each x-y pair is
graphed, generating multiple lines on the plot. The above plot command
allows vectors of different lengths to be displayed on the same graph.
MATLAB automatically scales the plots. Also, the plot remains as the current
plot until another plot is generated; in which case, the old plot is erased. The
hold command holds the current plot on the screen, and inhibits erasure and
rescaling. Subsequent plot commands will overplot on the original curves.
The hold command remains in effect until the command is issued again.
When a graph is drawn, one can add a grid, a title, a label and x- and y-axes
to the graph. The commands for grid, title, x-axis label, and y-axis label are
grid (grid lines), title (graph title), xlabel (x-axis label), and ylabel (y-axis
label), respectively. For example, Figure 2.2 can be titled, and axes labeled
with the following commands:
t = 0:0.5:4;
y = 6*exp(-2*t);
plot(t, y)
title('Response of an RC circuit')
xlabel('time in seconds')
ylabel('voltage in volts')
grid

To write text on a graphic screen beginning at a point (x, y) on the graphic
screen, one can use the command
text(x, y, ’text’)
For example, the statement
text(2.0, 1.5, ’transient analysis’)
will write the text, transient analysis, beginning at point (2.0,1.5). Multiple
text commands can be used. For example, the statements
plot(a1,b1,a2,b2)
text(x1,y1,’voltage’)
text(x2,y2,’power’)

will provide texts for two curves: a1 versus b1 and a2 versus b2. The text will
be at different locations on the screen provided x1 ≠ x2 or y1 ≠ y2.
If the default line-types used for graphing are not satisfactory, various symbols
may be selected. For example:
plot(a1, b1, ’*’)
draws a curve, a1 versus b1, using star(*) symbols, while
plot(a1, b1, ’*’, a2, b2, ’+’)
uses a star(*) for the first curve and the plus(+) symbol for the second curve.
Other print types are shown in Table 2.2.

CHAPTER TWO- PLOTTING COMMANDS

2.1 GRAPH FUNCTIONS


MATLAB has built-in functions that allow one to generate bar charts, x-y,
polar, contour and 3-D plots, and bar charts. MATLAB also allows one to
give titles to graphs, label the x- and y-axes, and add a grid to graphs. In
addition, there are commands for controlling the screen and scaling. Table 2.1
shows a list of MATLAB built-in graph functions. One can use MATLAB’s
help facility to get more information on the graph functions.

Table 2.1
Plotting Functions
FUNCTION
DESRIPTION
axis- freezes the axis limits
bar -plots bar chart
contour- performs contour plots
ginput- puts cross-hair input from mouse
grid- adds grid to a plot
gtext -does mouse positioned text
histogram -gives histogram bar graph
hold- holds plot (for overlaying other plots)
loglog- does log versus log plot
mesh- performs 3-D mesh plot
meshdom- domain for 3-D mesh plot
pause- wait between plots
plot- performs linear x-y plot
polar -performs polar plot
semilogx- does semilog x-y plot (x-axis logarithmic)
semilogy- does semilog x-y plot (y-axis logarithmic)
shg -shows graph screen
stairs- performs stair-step graph
text- positions text at a specified location on graph
title -used to put title on graph
xlabel- labels x-axis
ylabel -labels y-axis

1.6.2 Function Files

1.6.2 Function Files


Function files are m-files that are used to create new MATLAB functions.
Variables defined and manipulated inside a function file are local to the function,
and they do not operate globally on the workspace. However, arguments
may be passed into and out of a function file.
The general form of a function file isfunction variable(s) = function_name (arguments)
% help text in the usage of the function
%
.
.
end
To illustrate the usage of function files and rules for writing m-file function, let
us study the following two examples.
Example 1.3
Write a function file to solve the equivalent resistance of series connected resistors,
R1, R2, R3, …, Rn.
Solution:
MATLAB Script
function req = equiv_sr(r)
% equiv_sr is a function program for obtaining
% the equivalent resistance of series
% connected resistors
% usage: req = equiv_sr(r)
% r is an input vector of length n
% req is an output, the equivalent resistance(scalar)
%
n = length(r); % number of resistors
req = sum (r); % sum up all resistors
end
The above MATLAB script can be found in the function file equiv_sr.m,
which is available on the disk that accompanies this book.
Suppose we want to find the equivalent resistance of the series connected resistors
10, 20, 15, 16 and 5 ohms. The following statements can be typed in the
MATLAB command window to reference the function equiv_sr
a = [10 20 15 16 5];
Rseries = equiv_sr(a)
diary
The result obtained from MATLAB is
© 1999
Rseries =
66
Example 1.4
Write a MATLAB function to obtain the roots of the quadratic equation
ax2 + bx + c = 0
Solution:
MATLAB Script
function rt = rt_quad(coef)
%
% rt_quad is a function for obtaining the roots of
% of a quadratic equation
% usage: rt = rt_quad(coef)
% coef is the coefficients a,b,c of the quadratic
% equation ax*x + bx + c =0
% rt are the roots, vector of length 2
% coefficient a, b, c are obtained from vector coef
a = coef(1); b = coef(2); c = coef(3);
int = b^2 - 4*a*c;
if int > 0
srint = sqrt(int);
x1= (-b + srint)/(2*a);
x2= (-b - srint)/(2*a);
elseif int == 0
x1= -b/(2*a);
x2= x1;
elseif int < 0
srint = sqrt(-int);
p1 = -b/(2*a);
p2 = srint/(2*a);
x1 = p1+p2*j;
x2 = p1-p2*j;
end
rt =[x1;
x2];
end

1.6 M-FILES


Normally, when single line commands are entered, MATLAB processes the
commands immediately and displays the results. MATLAB is also capable of
processing a sequence of commands that are stored in files with extension m.
MATLAB files with extension m are called m-files. The latter are ASCII text
files, and they are created with a text editor or word processor. To list m-files
in the current directory on your disk, you can use the MATLAB command
what. The MATLAB command, type, can be used to show the contents of a
specified file. M-files can either be script files or function files. Both script
and function files contain a sequence of commands. However, function files
take arguments and return values.

1.6.1 Script files
Script files are especially useful for analysis and design problems that require
long sequences of MATLAB commands. With script file written using a text
editor or word processor, the file can be invoked by entering the name of the
m-file, without the extension. Statements in a script file operate globally on
the workspace data. Normally, when m-files are executing, the commands are
not displayed on screen. The MATLAB echo command can be used to view
m-files while they are executing. To illustrate the use of script file, a script
file will be written to simplify the following complex valued expression z.
Example 1.2
Simplify the complex number z and express it both in rectangular and polar
form.
z
j j
j j
=
+ + ∠
+ +
( )( )( )
( )( )
3 4 5 2 2 60
3 6 1 2
0
Solution:
The following program shows the script file that was used to evaluate the
complex number, z, and express the result in polar notation and rectangular
form.
MATLAB Script
diary ex1_2.dat


% Evaluation of Z
% the complex numbers are entered
Z1 = 3+4*j;
Z2 = 5+2*j;
theta = (60/180)*pi; % angle in radians
Z3 = 2*exp(j*theta);
Z4 = 3+6*j;
Z5 = 1+2*j;
% Z_rect is complex number Z in rectangular form
disp('Z in rectangular form is'); % displays text inside brackets
Z_rect = Z1*Z2*Z3/(Z4+Z5);
Z_rect
Z_mag = abs (Z_rect); % magnitude of Z
Z_angle = angle(Z_rect)*(180/pi); % Angle in degrees
disp('complex number Z in polar form, mag, phase'); % displays text
%inside brackets
Z_polar = [Z_mag, Z_angle]
diary
The program is named ex1_2.m. It is included in the disk that accompanies
this book. Execute it by typing ex1_2 in the MATLAB command window.
Observe the result, which should be
Z in rectangular form is
Z_rect =
1.9108 + 5.7095i
complex number Z in polar form (magnitude and phase) is
Z_polar =
6.0208 71.4966


1.5 THE COLON SYMBOL (:)

1.5 THE COLON SYMBOL (:)

The colon symbol (:) is one of the most important operators in MATLAB. It
can be used (1) to create vectors and matrices, (2) to specify sub-matrices and
vectors, and (3) to perform iterations. The statement
t1 = 1:6
will generate a row vector containing the numbers from 1 to 6 with unit increment.
MATLAB produces the result
t1 =
1 2 3 4 5 6
Non-unity, positive or negative increments, may be specified. For example,
the statement
t2 = 3:-0.5:1
will result in
t2 =
3.0000 2.5000 2.0000 1.5000 1.0000
The statement
t3 = [(0:2:10);(5:-0.2:4)]
will result in a 2-by-4 matrix
t3 =
0 2.0000 4.0000 6.0000 8.0000 10.0000
5.0000 4.8000 4.6000 4.4000 4.2000 4.0000
Other MATLAB functions for generating vectors are linspace and logspace.
Linspace generates linearly evenly spaced vectors, while logspace generates
logarithmically evenly spaced vectors. The usage of these functions is of the
form:
linspace(i_value, f_value, np)
logspace(i_value, f_value, np)
where
i_value is the initial value
f_value is the final value
np is the total number of elements in the vector.
For example,
t4 = linspace(2, 6, 8)
will generate the vector
t4 =
Columns 1 through 7
2.0000 2.5714 3.1429 3.7143 4.2857 4.8571
5.4286
Column 8
6.0000
Individual elements in a matrix can be referenced with subscripts inside parentheses.
For example, t2(4) is the fourth element of vector t2. Also, for matrix
t3, t3(2,3) denotes the entry in the second row and third column. Using the colon
as one of the subscripts denotes all of the corresponding row or column.
For example, t3(:,4) is the fourth column of matrix t3. Thus, the statement
t5 = t3(:,4)
will give
t5 =
6.0000
4.4000
Also, the statement t3(2,:) is the second row of matrix t3. That is the statement
t6 = t3(2,:)
will result in
t6 =
5.0000 4.8000 4.6000 4.4000 4.2000 4.0000
If the colon exists as the only subscript, such as t3(:), the latter denotes the
elements of matrix t3 strung out in a long column vector. Thus, the statement
t7 = t3(:)
will result in
t7 =
0
5.0000
2.0000
4.8000
4.0000
4.6000
6.0000
4.4000
8.0000
4.2000
10.0000
4.0000
Example 1.1
The voltage, v, across a resistance is given as (Ohm’s Law), v = Ri , where
i is the current and R the resistance. The power dissipated in resistor R is
given by the expression
P = Ri2
If R = 10 Ohms and the current is increased from 0 to 10 A with increments
of 2A, write a MATLAB program to generate a table of current, voltage and
power dissipation.
Solution:
MATLAB Script
diary ex1_1.dat
% diary causes output to be written into file ex1_1.dat
% Voltage and power calculation
R=10; % Resistance value
i=(0:2:10); % Generate current values
v=i.*R; % array multiplication to obtain voltage
p=(i.^2)*R; % power calculation
sol=[i v p] % current, voltage and power values are printed
diary
% the last diary command turns off the diary state
MATLAB produces the following result:
sol =
Columns 1 through 6
0 2 4 6 8 10
Columns 7 through 12
0 20 40 60 80 100
Columns 13 through 18
0 40 160 360 640 1000
Columns 1 through 6 constitute the current values, columns 7 through 12 are
the voltages, and columns 13 through 18 are the power dissipation values

1.4 COMPLEX NUMBERS

1.4 COMPLEX NUMBERS

MATLAB allows operations involving complex numbers. Complex numbers
are entered using function i or j. For example, a number z = 2 + j2 may be
entered in MATLAB as
z = 2+2*i
or
z = 2+2*j
Also, a complex number za
za = 2 2 exp[(π / 4) j]
can be entered in MATLAB as
za = 2*sqrt(2)*exp((pi/4)*j)
It should be noted that when complex numbers are entered as matrix elements
within brackets, one should avoid any blank spaces. For example,
y = 3 + j4 is represented in MATLAB as
y = 3+4*j
If spaces exist around the + sign, such as
u= 3 + 4*j
MATLAB considers it as two separate numbers, and y will not be equal to u.
If w is a complex matrix given as
w =
1 1 2 2
3 2 4 3
+ −
+ +
 
 
j j
j j
then we can represent it in MATLAB as
w = [1+j 2-2*j; 3+2*j 4+3*j]
which will produce the result
w =
1.0000 + 1.0000i 2.0000 - 2.0000i
3.0000 + 2.0000i 4.0000 + 3.0000i
If the entries in a matrix are complex, then the “prime” (‘) operator produces
the conjugate transpose. Thus,
wp = w'
will produce
wp =
1.0000 - 1.0000i 3.0000 - 2.0000i
2.0000 + 2.0000i 4.0000 - 3.0000i
For the unconjugate transpose of a complex matrix, we can use the point transpose
(.’) command. For example,
wt = w.'
will yield
© 1999
wt =
1.0000 + 1.0000i 3.0000 + 2.0000i
2.0000 - 2.0000i 4.0000 + 3.0000i

1.3 ARRAY OPERATIONS

1.3 ARRAY OPERATIONS


Array operations refer to element-by-element arithmetic operations. Preceding
the linear algebraic matrix operations, * / \ ‘ , by a period (.) indicates an array
or element-by-element operation. Thus, the operators .* , .\ , ./, .^ , represent
element-by-element multiplication, left division, right division, and raising to
the power, respectively. For addition and subtraction, the array and matrix operations
are the same. Thus, + and .+ can be regarded as an array or matrix
addition.
If A1 and B1 are matrices of the same dimensions, then A1.*B1 denotes an array
whose elements are products of the corresponding elements of A1 and B1.
Thus, if
A1 = [2 7 6
8 9 10];
B1 = [6 4 3
2 3 4];
then
C1 = A1.*B1
results in
C1 =
12 28 18
16 27 40
An array operation for left and right division also involves element-by-element
operation. The expressions A1./B1 and A1.\B1 give the quotient of elementby-
element division of matrices A1 and B1. The statementD1 = A1./B1
gives the result
D1 =
0.3333 1.7500 2.0000
4.0000 3.0000 2.5000
and the statement
E1 = A1.\B1
gives
E1 =
3.0000 0.5714 0.5000
0.2500 0.3333 0.4000
The array operation of raising to the power is denoted by .^. The general
statement will be of the form:
q = r1.^s1
If r1 and s1 are matrices of the same dimensions, then the result q is also a matrix
of the same dimensions. For example, if
r1 = [ 7 3 5];
s1 = [ 2 4 3];
then
q1 = r1.^s1
gives the result
q1 =
49 81 125
© 1999
One of the operands can be scalar. For example,
q2 = r1.^2
q3 = (2).^s1
will give
q2 =
49 9 25
and
q3 =
4 16 8
Note that when one of the operands is scalar, the resulting matrix will have the
same dimensions as the matrix operand.

1.2 MATRIX OPERATIONS
The basic matrix operations are addition(+), subtraction(-), multiplication (*),
and conjugate transpose(‘) of matrices. In addition to the above basic operations,
MATLAB has two forms of matrix division: the left inverse operator \
or the right inverse operator /.
Matrices of the same dimension may be subtracted or added. Thus if E and F
are entered in MATLAB as
E = [7 2 3; 4 3 6; 8 1 5];
F = [1 4 2; 6 7 5; 1 9 1];
and
G = E - F
H = E + F
then, matrices G and H will appear on the screen as
G =
6 -2 1
-2 -4 1
7 -8 4
H =
8 6 5
10 10 11
9 10 6
A scalar (1-by-1 matrix) may be added to or subtracted from a matrix. In this
particular case, the scalar is added to or subtracted from all the elements of another
matrix. For example,
J = H + 1
gives
J =
9 7 6
11 11 12
10 11 7
Matrix multiplication is defined provided the inner dimensions of the two operands
are the same. Thus, if X is an n-by-m matrix and Y is i-by-j matrix


X*Y is defined provided m is equal to i. Since E and F are 3-by-3 matrices,
the product
Q = E*F
results as
Q =
22 69 27
28 91 29
19 84 26
Any matrix can be multiplied by a scalar. For example,
2*Q
gives
ans =
44 138 54
56 182 58
38 168 52
Note that if a variable name and the “=” sign are omitted, a variable name ans
is automatically created.
Matrix division can either be the left division operator \ or the right division
operator /. The right division a/b, for instance, is algebraically equivalent to
a
b
while the left division a\b is algebraically equivalent to
b
a
.
If Z * I = V and Z is non-singular, the left division, Z\V is equivalent to
MATLAB expression
I = inv(Z) *V
where inv is the MATLAB function for obtaining the inverse of a matrix. The
right division denoted by V/Z is equivalent to the MATLAB expression
I = V *inv(Z)
There are MATLAB functions that can be used to produce special matrices.
Examples are given in Table 1.3.


1.1 MATLAB BASIC OPERATIONS


When MATLAB is invoked, the command window will display the prompt >>.
MATLAB is then ready for entering data or executing commands. To quit
MATLAB, type the command

exit or quit

MATLAB has on-line help. To see the list of MATLAB’s help facility, type

help


The help command followed by a function name is used to obtain information
on a specific MATLAB function. For example, to obtain information on
the use of fast Fourier transform function, fft, one can type the command

help fft


The basic data object in MATLAB is a rectangular numerical matrix with real
or complex elements. Scalars are thought of as a 1-by-1 matrix. Vectors are
considered as matrices with a row or column. MATLAB has no dimension
statement or type declarations. Storage of data and variables is allocated
automatically once the data and variables are used.

MATLAB statements are normally of the form:

variable = expression


Expressions typed by the user are interpreted and immediately evaluated by the
MATLAB system. If a MATLAB statement ends with a semicolon, MATLAB
evaluates the statement but suppresses the display of the results. MATLAB
is also capable of executing a number of commands that are stored in a file.
This will be discussed in Section 1.6. A matrix


A =
1 2 3
2 3 4
3 4 5






may be entered as follows:


A = [1 2 3; 2 3 4; 3 4 5];
Note that the matrix entries must be surrounded by brackets [ ] with row
elements separated by blanks or by commas. The end of each row, with the
exception of the last row, is indicated by a semicolon. A matrix A can also be
entered across three input lines as


A = [ 1 2 3
2 3 4
3 4 5];

In this case, the carriage returns replace the semicolons. A row vector B with
four elements

B = [ 6 9 12 15 18}
can be entered in MATLAB as
B = [6 9 12 15 18];
or

B = [6 , 9,12,15,18]
For readability, it is better to use spaces rather than commas between the elements.
The row vector B can be turned into a column vector by transposition,
which is obtained by typing
C = B’



The above results in
C =
6
9
12
15
18






Other ways of entering the column vector C are
C = [6
9
12
15
18]


or
C = [6; 9; 12; 15; 18]


MATLAB is case sensitive in naming variables, commands and functions.
Thus b and B are not the same variable. If you do not want MATLAB to be
case sensitive, you can use the command

casesen off


To obtain the size of a specific variable, type size ( ). For example, to find the
size of matrix A, you can execute the following command:

size(A)

The result will be a row vector with two entries. The first is the number of
rows in A, the second the number of columns in A.
To find the list of variables that have been used in a MATLAB session, type
the command
whos
There will be a display of variable names and dimensions. Table 1.1 shows
the display of the variables that have been used so far in this book:








MATLAB FUNDAMENTALS

MATLAB FUNDAMENTALS

MATLAB is a numeric computation software for engineering and scientific
calculations. The name MATLAB stands for MATRIX LABORATORY.
MATLAB is primarily a tool for matrix computations. It was developed by
John Little and Cleve Moler of MathWorks, Inc. MATLAB was originally
written to provide easy access to the matrix computation software packages
LINPACK and EISPACK.

MATLAB is a high-level language whose basic data type is a matrix that does
not require dimensioning. There is no compilation and linking as is done in
high-level languages, such as C or FORTRAN. Computer solutions in
MATLAB seem to be much quicker than those of a high-level language such
as C or FORTRAN. All computations are performed in complex-valued double
precision arithmetic to guarantee high accuracy.

MATLAB has a rich set of plotting capabilities. The graphics are integrated in
MATLAB. Since MATLAB is also a programming environment, a user can
extend the functional capabilities of MATLAB by writing new modules.
MATLAB has a large collection of toolboxes in a variety of domains. Some
examples of MATLAB toolboxes are control system, signal processing, neural
network, image processing, and system identification. The toolboxes consist
of functions that can be used to perform computations in a specific domain.