technical computing laboratory manual
DESCRIPTION
For Computer programming subject especially for engineering students.TRANSCRIPT
1
Experiment No. 1: INTRODUCTION TO MATLAB®
OBJECTIVES
1. Become familiar with the basic windows of MATLAB® and their functions
and operations.
2. Perform scalar operations using MATLAB®
INTRODUCTION
Matrix Laboratory - MATLAB
A high-level language for technical computing.
It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation.
Stands for matrix laboratory
MATLAB® Windows
Command Window
Use to enter variables and run functions and M-files.
Command History
Statements you enter in the Command Window are logged in the
Command History. In the Command History, you can view previously run
statements, and copy and execute selected statements.
Workspace Browser
The MATLAB workspace consists of the set of variables (named arrays)
built up during a MATLAB session and stored in memory. You add
variables to the workspace by using functions, running M-files, and
loading saved workspaces.
Current Directory Window
Use to view files and subdirectories under a main directory.
Editor/Debugger Window
Use for writing and editing functions and programs.
2
Figure Window
The Figure Window opens automatically when graphics commands are
executed, and contains graphs created by these commands.
Assignment Operator ( = )
Variable_name = A numerical value, or a computable
expression
Variables
A variable in MATLAB may be in the form of a scalar quantity, vector
quantity, or a matrix.
MATLAB does not require any type of variable declarations or dimension
statements. When MATLAB encounters a new variable name, it
automatically creates the variable and allocates the appropriate amount of
storage. The variable list can be found in workspace window. If the
variable already exists, MATLAB changes its contents and, if necessary,
allocates new storage.
Eg. >> xnum = 23;
Rules in Creating Variables
Can be up to 63 (in MATLAB® 6.5) characters long (31 characters in
MATLAB® 6.0).
Can contain letters, digits, and the underscore character.
Must begin with a letter.
MATLAB is case sensitive; For example, AA, Aa, aA, and aa are the
names of four different variables.
Avoid using the names of built-in function for a variable (i.e. avoid using:
cos, sin, exp, sqrt, etc.). Once a function name is used to
define a variable, the function cannot be used.
3
Predefined Variables
ans A variable that has the value of the last expression that was
not assigned to a specific variable. If the user does not
assign the value of an expression to a variable, MATLAB
automatically stores the result in ans.
pi The number π.
eps The smallest difference between two numbers.
Equals 2^(-52), which is approximately 2.2204e-016.
inf Used for infinity.
i Square root of -1, which is: 0 + 1.0000i.
j Same as i.
NaN Stands for Not-a-Number. Used when MATLAB cannot
determine a valid numeric value. For example 0/0.
realmax largest positive floating point number i.e. 1.7977e+308
realmin smallest positive floating point number i.e. 2.2251e-308.
Numbers
MATLAB uses conventional decimal notation, with an optional decimal
point and leading plus or minus sign, for numbers. Scientific notation uses
the letter e to specify a power-of-ten scale factor. Imaginary numbers use
either i or j as a suffix.
Eg. 5, -88, 0.0001, 3.63938, 1.23410e-20,
6.02252e23, 3i, 4.23j
All numbers are stored internally using the long format specified by the
IEEE floating-point standard. Floating-point numbers have a finite
precision of roughly 16 significant decimal digits and a finite range of
roughly 10-308
to 10+308
4
Arithmetic Scalar Operators
Expressions use familiar arithmetic operators and precedence rules.
+ Addition
- Subtraction
* Multiplication
/ Division
^ Power (exponentiation)
( ) Specify evaluation order
To define a scalar quantity
>> a = 2; the variable ‘a’ is a scalar with a value of 2 (1-by-1 matrix)
>> b = 1;
>> y = a^2+(b/3)-1
Built-in Math Functions
Function Description Example
sin(x) Sine of angle x (x in
radians).
>> sin(pi/6)
ans = 0.5000
cos(x) Cosine of angle x (x in
radians).
>> cos(pi/6)
ans = 0.8660
tan(x) Tangent of angle x (x in
radians).
>> tan(pi/6)
ans = 0.5774
cot(x) Cotangent of angle x (x
in radians).
>> cot(pi/6)
ans = 1.7321
Function Description Example
sqrt(x) Square root. >> sqrt(81)
ans = 9
exp(x) Exponential (ex). >> exp(5)
ans = 148.4132
5
abs(x) Absolute value. >> abs(-24)
ans = 24
log(x) Natural logarithm.
Base e logarithm (ln).
>> log(1000)
ans = 6.9078
log10(x) Base 10 logarithm. >> log10(1000)
ans = 3.0000
factorial(x) The factorial function x!
(x must be a positive integer.)
>> factorial(5)
ans = 120
Display Format
Command Description Example
format short Fixed-point with 4 decimal
digits
>> 290/7
ans =
41.4286
format long Fixed-point with 14 decimal
digits
>> 290/7
ans =
41.42857142857143
format short e Scientific notation with 4
decimal digits.
>> 290/7
ans =
4.1429e+001
format long e Scientific notation with 15
decimal digits.
>> 290/7
ans =
4.142857142857143e+001
format rat Rational form >> 290/7
ans = 290/7
6
EXERCISES
A. Convert the following arithmetic expressions to MATLAB expressions that evaluate
to the same value.
1. )3)(3(
1512 +
2. 411
4416 −+
3.
4
1
8
1
11
++
4. o
oo
30tan
25cos30sin +
5. o80cos
323456 35 +
B. Evaluate the following mathematical expressions using the command window
1. V = 3
3
4Rπ , for R = 2 meters
2. )ln( 32 xey x += + , for x = 1.5
3. ( )
)6/tan(
)4/cos(3/sin
πππ +
in rational form
7
Experiment No. 2: VECTOR AND MATRIX OPERATIONS
OBJECTIVES
1. To be able to perform basic vector arithmetic operations using MATLAB®
2. To be able to perform basic matrix operations using MATLAB®
INTRODUCTION
In linear algebra, vector is defined as an m-by-1 or 1-by-n array of elements
where m > 1 and n > 1 while matrix is defined as any m-by-n array of
elements where m > 1 and n > 1
To define a vector quantity, x and y
>> x = [1 2 3] the variable ‘B’ is a row vector (1-by-3 matrix)
x = 321
>> y = [1; 2; 3] the variable ‘C’ is a column vector (3-by-1 matrix)
y =
3
2
1
To define a vector quantity using colon operator
>> x1 = [0:2:10]
>> y1 = [0:2:10]’
To define a vector quantity using linspace( ) function
>> x2 = linspace(0,10,5)
>> y2 = linspace(0,10,5)’
To define a matrix, A which is a 3-by-3 matrix:
>> A = [1 2 3; 4 5 6; 7 8 9]
8
A =
987
654
321
Generating Arrays using the built-in functions of MATLAB®
Vector and Array Addressing
Vector
>> v = [1 2 3 6 7 8]
>> v4 = v(4)
>> v6 = v(6)
Matrix
>> E = [1 2 3;4 5 6;7 8 9]
E =
987
654
321
>> e23 = E(2,3)
>> e32 = E(3,2)
SYNTAX DESCRIPTION
eye (n) Creates an n-by-n identity matrix
ones (m,n) Creates an m-by-n matrix all elements have value of 1
rand (m,n) Creates an m-by-n matrix all elements of which are of
uniformly distributed random values ranging from 0 to 1
zeros(m,n) Creates an m-by-n matrix all elements have value of zero
randn(m,n) Creates an m-by-n matrix all elements of which are of
normally distributed random values with zero mean and
variance of 1
9
Using a Colon
a. Vector
v(:) – refers to all elements of the vector v
v(m:n) – refers to elements m through n of the vector v
if v = 1 2 3 6 7 8 then v(2:5) = 2 3 6 7
b. Matrix
A(:,n) - Returns the elements of all the rows in column n of
matrix A.
A(n,:) - Returns the elements of all the columns in row n of
matrix A.
A(:,m:n) - Returns the elements of all the rows from column m
to column n of matrix A.
A(m:n,:) - Returns the elements of all the columns from row m
to row n of matrix A.
A(m:n,p:q) - Returns the elements from row m to row n and
from column p to column q of matrix A
2. Addition and Subtraction of Vectors and Arrays
Addition and subtraction require both vectors and both matrices to have
the same dimension, or one of them must be a scalar. If the dimensions are
incompatible, an error results.
Example 1:
>> v1 = [1 2 3 4 5];
>> v2 = [1 1 1 1 1];
>> vx = v1 + v2
>> vy = v1 – v2
Example 2:
>> A = [1 2 3;1 0 1;-1 1 2];
>> B = [1 1 1; 1 1 -1;0 0 1];
10
>> C = A + B
>> D = A – B
3. Multiplication of Vectors
a. Dot product / Scalar product
Also known as inner product
Produced by multiplying a row vector to a column vector
The result is a scalar quantity
b. Outer product
Produced by multiplying a column vector to a row vector
The result is a matrix
4. Multiplication of Matrix
The matrix product C = AB is defined when the column
dimension of A is equal to the row dimension of B, or when one of
them is a scalar. If A is m-by-p and B is p-by-n, their product C is
m-by-n
Matrix multiplication is not commutative.
5. Transpose of a Matrix
The transpose operation interchanges aij and aji
MATLAB uses apostrophe (or single quote) to denote transpose
6. Array Operations
Element-by-element operations
>> a = [1 2 3];
>> b = [1 2 3];
a. Multiplication
>> c = a.*b
11
b. Division
>> c = a./b
c. Exponentiation
>> c = a.^b
EXERCISES
For the following exercises, write a simple program in the MATLAB command window
and execute your program.
1. Let x = [2 4 6 8 10] and y = [1 3 5 7 9]. Compute for vector z whose elements
are equal to
Create matrix C:
=
352821147
1512963
108642
C
Using array addressing, use matrix C to:
a. Create a three-element column vector named col_a that contains the
elements of the third column of C.
b. Create a five-element column vector named col_b that contains the
elements of the second row of C.
c. Create a 2x3 matrix named mat_B from the first and 2nd
rows, and the
2nd
, 3rd
and 4th
columns of the matrix C.
yx
xyyx
x
yxy
z /
)(10
)(+
+
+=
−
12
2. Generate the following matrices:
304
693
261
XMatrix
371
502
491
YMatrix
−
529
132
473
ZMatrix
Determine the following:
a. transpose of X
b. matrix X added to matrix Z
c. matrix Y subtracted from matrix Z
d. matrix X multiplied by matrix Y
e. matrix X element-by-element multiplied by matrix Y
f. matrix Y divided by matrix Z
g. matrix Y element-by-element divided by matrix Z.
13
Experiment No. 3 SCRIPT FILES
OBJECTIVES
1. To be able to create simple programs under MATLAB® environment.
2. To be able to perform basic MATLAB® operations using M-files.
INTRODUCTION
SCRIPT FILES
A script file is a sequence of MATLAB commands it is also called a
program.
A script file is also known as M file because the extension .m is used when
they are saved.
A script file is created and edited in the Editor/Debugger Window.
Before a script file can be executed it has to be saved.
A script can be executed either by typing its name in the command
window and pressing Enter key, or directly from the Editor/Debugger
Window by clicking on the Run icon.
Input to a Script File
When a script file is executed the variables that are used in the calculations within
the file must have assigned values. There are three possible ways to assign a value
to a variable.
1. The variable is defined and assigned value in the script file
The assignment of value to the variable is part of the script file.
2. The variable is defined and assigned value in the command window.
The assignment of a value to the variable is done in the command
window.
3. The variable is defined in the script file, but a specific value is entered in
the command window when the script file is executed.
14
The variable is defined in the script file and when the file is executed, the
user is prompted to assign a value to the variable in the command window.
It uses the input() command.
Syntax:
variable_name = input(‘message string’) or
variable_name = input(‘message string’,’s’)
when the variable is assigned to be a string.
Output Commands
The disp() command
is used to display the elements of a variable without displaying the name
of the variable
Syntax: disp(variable_name) or
disp(‘text as string’)
The fprintf() command
is used to display output on the screen or to save it to a file.
It is also used to format the output
It is also used to save output to a file
Syntax: fprintf(‘text as string %5.2f additional
text’,variable_name)
Where: % : marks the spot where the number is inserted within the
text.
5 : field width (optional) –specifies minimum number of
digits
2 : precision (optional) – number of digits to the right of
decimal point
f : conversion character (required)
15
EXERCISES
1. Create a script file that will accept a value in metric unit (mass in kgs, and volume
cubic meter) and will output the equivalent density in lb/cu.ft.
2. Create a script file that will accept a volume (V), and a height (h) of a right
circular cone and will display the radius (r) of the base of the cone and the surface
area (S).
V = hr 2
3
1π S = 22 hrr +π
3. Write a script file that will compute the sin of an angle using the Taylor series
formula: ∑=
+
+−
=n
k
kk
k
xx
0
12
)!12(
)1(sin The program will prompt the user to input the
angle x in degrees, and n the number of terms in the series. Use the program to
calculate sin(150o) using 5 and 9 terms.
4. Write a script file that determines the angles of a triangle when the lengths of the
sides are given. The program will prompt the user to enter the sides of the triangle
a, b, and c and the program will display the internal angles A, B, and C of
the triangle in degrees. Use the function to determine the angles in triangles with
the following sides.
a. a = 10, b = 15, c = 7
b. a = 6, b = 8, c = 10
c. a = 200, b = 75, c = 250
16
Experiment No. 4 FUNCTION FILES
OBJECTIVES
1. To be able to create functions or subroutines under MATLAB® environment.
2. To be able to perform basic MATLAB® operations using M-files.
INTRODUCTION
FUNCTION FILES
A function file is also known as a subroutine – a special program which
has a specific function. Eg. sin(), sqrt(), atan()
It is a subprogram within a computer program.
A function file is also an M-file because the extension .m is used when
they are saved.
A function file is created and edited also in the Editor/Debugger Window.
Structure of Function File
1. Function Definition Line
It is the first executable line which defines the file as a function file and
not a script file.
Absence of function definition line means that the file is a script file.
It defines the function name.
It defines the number and order of the input and output arguments.
General Form:
function [output arguments] = function_name
(input arguments)
17
2. H1 Line and Help Text Lines (Optional)
Are the comment lines (lines that begins with % sign) following the
function definition line.
Provides information about the function
H1 line – is the first comment line usually contains the function name and
a short definition of the function.
Help text lines – are comment lines that follow the H1 line. It contains
explanations of the function regarding with the input and output
arguments.
The H1 line and help text lines are displayed in the command window
when the user typed
>> help function_name
3. Function Body
Contains the computer program that actually performs the computations.
Local Variables
Variables inside a function file and do not recognize in the command window.
Comparison between Function File and Script files
Both Script and Function files are saved with extension name .m
The first line in the function file is the function definition line
The variables in the function files are local. The variables in the script file are
recognized in the command window.
Script files can use variables that have been defined in the workspace.
18
EXERCISES
1. Create a function file that will accept a value in metric unit (mass in kgs, and
volume cubic meter) and will output the equivalent density in lb/cu.ft. For the
function name and arguments use:
D = density(M,V)
where D is the density, M is the mass and V is the volume.
2. Create a script file that will accept a volume (V), and a height (h) of a right
circular cone and will display the radius (r) of the base of the cone and the surface
area (S). For the function name and arguments use:
[r,S] = radius_area(h,V)
where r is the radius, S is the surface area, h is the height and V is the volume.
V = hr 2
3
1π S = 22 hrr +π
3. The function sin(x) can be written as a Taylor series expanded form i.e.:
∑=
+
+−
=0
12
)!12(
)1(sin
k
kk
k
xx Write a user defined function file that calculates sin(x)
by using the Taylor series. For the function name and arguments use:
y = my_sin(x,n). The input arguments are the angle x in degrees, and n the
number of terms in the series. Use the function to calculate sin(150o) using 5
and 9 terms and compare the result by using the built-in function y = sin(x).
4. Write a user-defined MATLAB function that determines the angles of a triangle
when the lengths of the sides are given. For the function name and arguments use
[A,B,C] = triangle(a,b,c). Use the function to determine the angles in
triangles with the following sides.
a. a = 10, b = 15, c = 7
b. a = 6, b = 8, c = 10
c. a = 200, b = 75, c = 250
19
Experiment No. 5: MATLAB® PROGRAMMING
OBJECTIVE
1. To become familiar with the programming environment of MATLAB®.
2. To apply programming skills in MATLAB®.
INTRODUCTION
PROGRAMMING in MATLAB®
Relational Operators
Relational Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
= = Equal to
~ = Not equal to
Logical Operators
Logical Operator Description
& AND
| OR
~ NOT
xor(A,B) Exclusive or
20
Order of Precedence
Precedence Operation
1 (highest) Parentheses ( )
2 Exponentiation
3 Logical NOT (~)
4 Multiplication, Division
5 Addition, Subtraction
6 Relational Operators
7 Logical AND (&)
8 (lowest) Logical OR ( | )
Built-in Logical Functions
Function Description
and(A,B) Equivalent to A & B
or(A,B) Equivalent to A | B
not(A) Equivalent to ~ A
xor(A,B) Exclusive or. Returns true if one operand
is true and the other is false.
all(A) Returns true if all elements in a vector A
are true. Returns false if one or more
elements are false.
any(A) Returns true if any element in a vector A
is true. Returns false if all elements are
false.
find(A) If A is a vector, returns the indices of the
nonzero elements.
find(A>b) If A is a vector, returns the address of the
elements that are larger than b.
21
Logical Operators
INPUT OUTPUT
A B AND OR XOR NOT A NOT B
F F F F F T T
F T F T T T F
T F F T T F T
T T T T F F F
Conditional Statements
1. The if-end Structure
if conditional expression
command 1
command 2
:
command n
end
2. The if-else-end Structure
if conditional expression
command 1
command 2
:
command n
else
command 1’
command 2’
command n’
3. The if-elseif-else-end Structure
if conditional expression 1
command 1
command 2
:
command n
elseif conditional
expression2
command 1’
command 2’
:
command n’
else
command 1’’
command 2’’
:
command n’’
end
end
22
The switch-case Statement
Provides a means for choosing one group of commands for execution out of
several possible groups.
switch switch expression
case value 1
command 1
:
command n
case value 2
command 1
:
command n
case value 3
command 1
:
command n
otherwise%optional
command 1
:
command n
end
Loop Commands
1. for-end Loop
for k = i:s:f
command 1
:
command n
end
where: i – initial value
s – interval or interval
f – final value
23
2. while-end Loop
while conditional expression
command 1
:
command n
end
24
EXERCISES
1. Write a program in a script file that determines the real roots of a quadratic
equation 02 =++ cbxax . Name the file quadroots. When the file runs it
asks the user to enter the values of the constants a, b, and c. To calculate
the roots of the equation the program calculates the discriminant D given by:
acbD 42 −=
If D > 0 the program displays a message: “The equation has two roots”, and
the roots are displayed in the next line.
If D = 0 the program displays a message: “The equation has one root”, and
the root is displayed in the next line.
If D < 0 the program displays a message: “The equation has no real roots”
Run the program using the following equations:
a. 0382 2 =−+ xx
b. 051015 2 =++ xx
c. 021218 2 =++ xx
2. The function xexf =)( can be represented in a Taylor series by:
∑=
=0 !n
nx
n
xe Write a program in a script file that determines ex by using the
Taylor series representation. The program calculates ex by adding terms of the
series and stopping when the absolute value of the term that was added last is
smaller than 0.0001. Use a while-end loop, but limit the number of passes to
30. If in the 30th
pass the value of the term that is added is not smaller than
0.0001, the program stops and displays a message that more than 30 terms are
needed. Use the program to calculate e2, e
–4, and e
21.
3. Create a function file that accepts a vector of any length and return a vector
whose elements are arranged in descending order. For the function name and
arguments use b = downsort(a) where a is the input vector and b is the
output vector. Do not use the MATLAB built-in sort function.
25
Experiment No. 6: TWO-DIMENSIONAL (2-D) PLOTS
OBJECTIVES
1. To be able to generate two-dimensional plots using MATLAB®
2. To be able to visualize graphically common functions in y = f(x) form
INTRODUCTION
1. Plot
The basic plotting function accepts character-string arguments that specify
various line styles, marker symbols, and colors for each vector plotted. In
the general form
plot(x,y,’line style_marker_color’)
where x – horizontal axis (vector)
y – vertical axis (vector)
x and y must have the same length
Line Specifiers
Used to define the style and color of the line and the type of
markers.
Line Style Specifier
Solid (default) -
Dashed --
Dotted :
Dash-dot -.
26
Line Color Specifier
Red r
Green g
Blue (default) b
Cyan c
Magenta m
Yellow y
Black k
White w
Marker Type Specifier
Plus sign +
Circle o
Asterisk *
Point .
Square s
Diamond d
Five-pointed star p
Six-pointed star h
Property Name Description Property Value
linewidth Specifies the width of the
line
A number in units of points
(default 0.5)
markersize Specifies the size of the
marker
A number in units of points
27
markeredgecolor Specifies the color of the
marker, or the color of the
edge line for filled markers
Color specifiers from the
table above, typed as a string
markerfacecolor Specifies the color of the
filling for filled markers
Color specifiers from the
table above, typed as a string
Example:
Creates a plot that connects the points with a solid line(-), color magenta (m) and
circle (o) as markers at the points. The line width is 2 points and the size of the
circle markers is 12 points. The markers have a green (g) edge line and yellow (y)
filling.
>> x = [0:0.5:5];
>> y = 2.^x+1;
>> plot(x,y,’mo’,’linewidth’,2,’markersize’,12,
’markeredgecolor’,’g’,’markerfacecolor’,’y’)
Useful commands
1. stem(x,y) - Plots discrete sequence data
2. hold on - it retains the current plot and its properties and allows the user
to plot additional graphs on the same figure window.
3. line(x,y) – adds the line in vectors x and y to the current axes.
4. xlabel(‘text’) – adds label on the horizontal axis of the current graph
5. ylabel(‘text’) – adds label on the vertical axis of the current graph
28
6. title(‘text’) – adds title on the current graph
7. legend(‘text1’,’text2’,…) – puts a legend on the current plot
8. grid on – adds grid on the current plot
9. semilogx(x,y) – plots y versus x with a log (base 10) scale for the y axis
10. semilogy(x,y) – plots y versus x with a log (base 10) scale for the x axis
11. loglog(x,y) – plots y versus x with a log (base 10) scale for both axes
12. bar(x,y) – vertical bar plot
13. barh(x,y) – horizontal bar plot
14. pie(x) – pie plot, where x is a row vector which specifies the division of
pie.
15. hist(y) – histogram, where y is a row vector.
16. polar(theta,radius) – polar plot, where theta and radius are vectors.
17. subplot(m,n,p) – plots multiple graphs on the same page with a number
of mxn plots with size of m rows and n columns at position p.
29
EXERCISES
Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
1. Plot the function 1
1)(
2
2
++
+−=
xx
xxxf for 1010 <<− x
2. Plot the following functions using polar plot in a single plot using the following
conditions
a. θsin21+=r , for πθ 60 << . Use red dash-dot line for the plot.
b. θsin21−=r , for πθ 60 << . Use black solid line for the plot.
c. θcos21+=r , for πθ 60 << . Use green dash-dot line for the plot.
d. θcos21−=r , for πθ 60 << . Use yellow solid line for the plot.
3. An electrical circuit that includes a voltage source E with an internal resistance r,
and a load resistance R is shown in the figure. Plot the power P as a function of R
for Ω<<Ω 101 R given that E = 12V and r = 2.5Ω. Prove that maximum power
transfer will occur when the internal resistance, r and load resistance R are equal.
4. Given the function 210xey −= for 200 << x , compare the graphs using the
function plot() and using log scale plot.
30
Experiment No. 7: THREE DIMENSIONAL (3-D) PLOTS
OBJECTIVE
1. To be able to present data in graphical form consisting of more than two
independent variables
INTRODUCTION
3-D Line-Plot
A line that is obtained by connecting points in a 3-D space.
Syntax:
plot3(x,y,z,’line specifiers’,’PropertyName’
,property value)
x, y and z – vectors of the coordinates of the points. (must have the
same number of elements)
Example
>> t = 0:0.1:6*pi;
>> x = sqrt(t).*sin(2*t);
>> y = sqrt(t).*cos(2*t);
>> z = 0.5*t;
>> plot3(x,y,z,’k’,’linewidth’,1)
>> grid on
>> xlabel(‘x’); ylabel(‘y’); zlabel(‘z’)
3-D Mesh and Surface Plots
Used for plotting functions of the form Z = f(X,Y) where the X and Y are
the independent variables and Z is the dependent variable.
31
Steps:
1. Creating a grid in the x-y plane
[X,Y] = meshgrid(x,y)
X is the matrix of the x – coordinates of the grid points.
Y is the matrix of the y – coordinates of the grid points.
x is the vector that divides the domain of x.
y is the vector that divides the domain of y.
2. Calculating the value of z at each point of the grid.
Z is calculated using element-by-element calculations.
Z = f(X,Y) note that the matrix X and Y must be of the same size.
3. Making mesh and surface plots
Once the three matrices exist (X,Y and Z), they can be used to plot mesh or
surface plots.
Syntax:
mesh(X,Y,Z) or surf(X,Y,Z)
X,Y are matrices with the coordinates of the grid and Z is a matrix with
the value of z at the grid points.
Other Mesh and Surface Plot Commands
meshz(X,Y,Z) mesh curtain plot
meshc(X,Y,Z) mesh and contour plot
surfc(X,Y,Z) surface and contour plot
surfl(X,Y,Z) surface plot with lighting
waterfall(X,Y,Z) waterfall plot – draws a mesh in one direction
only
32
contour3(X,Y,Z,n) 3-D contour plot – n is the number of contour
levels (optional)
contour(X,Y,Z,n) 2-D contour plot – n is the number of contour
levels (optional)
EXERCISES
Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
1. Plot the function )sin(10228.0
xzyx +−= for 22 <<− x and 22 <<− y . Use the
following commands and compare each plot
a. mesh(X,Y,Z)
b. meshz(X,Y,Z)
c. meshc(X,Y,Z)
d. surf(X,Y,Z)
e. surfc(X,Y,Z)
f. surfl(X,Y,Z)
g. waterfall(X,Y,Z)
h. contour3(X,Y,Z,50)
i. contour(X,Y,Z,50)
2. Plot the following functions in 3D using plot3 command for 55 <<− t
bt
at
at
ez
twey
twex
=
=
=
cos
sin
33
a. Use 2.0−=a , 2.0−=b and 5=w
b. Use 5.0−=a , 2.0−=b and 5=w
c. Use 2.0−=a , 2.0−=b and 10=w
d. Use 2.0−=a , 7.0−=b and 5=w
Compare all the generated graphs from one to another and explain the effects
of changing a, b, and w
34
Experiment No. 8: POLYNOMIAL OPERATIONS
OBJECTIVE
1. To be familiar with different elementary polynomial operations of
MATLAB®
2. To be able to solve mathematical problems involving polynomials using
MATLAB®
INTRODUCTION
Polynomials
Polynomials are functions that have the form:
01
1
1 ....)( axaxaxaxf n
n
n
n ++++= −−
Examples are:
1042)(
3765)(
2
25
+−=
+++=
zzzH
zzzzX
The representations of these polynomials in MATLAB are:
p = [5 0 0 6 7 3]
q = [2 -4 10]
Useful Commands:
polyval(p,x) – evaluates the value of a polynomial for a given value of x
o p – is a vector with the coefficients of the polynomial.
o x – is a number, or a variable that has an assigned value.
conv(h,x) – performs multiplication of two polynomial functions h and x
35
[q,r] = deconv(u,v) – performs division of two polynomial
functions where
o u – numerator polynomial
o v – denominator polynomial
o q – quotient polynomial
o r – remainder polynomial
roots(p) – computes for the roots of the polynomial equation p
poly(r) – generates the polynomial expansion given the roots r
[r,p,k] = residue(b,a) – computes the partial fraction expanded
form of a given rational polynomial function b and a
o b – numerator polynomial
o a – denominator polynomial
o r – coefficients of partial fraction expanded form
o p – roots (factors) of the polynomial a
o k – direct term coefficient when the degree of b is greater than or
equal to the degree of a
ARITHMETIC OPERATIONS OF POLYNOMIALS
Addition / Subtraction of Polynomials
Two polynomials can be added (or subtracted) by adding the vectors of the
coefficients.
If the polynomials are not of the same order, the shorter vector has to be
modified to be of the same length as the longer vector by adding zeros in
front (called padding)
36
Examples: solve f1(x) + f2(x)
122153)( 346
1 −+−+= xxxxxf
325)( 234
2 +−++= xxxxxf
Multiplication of Polynomials
Syntax: c = conv(a,b)
c – is a vector of the coefficients of the polynomial that is the product of
the multiplication.
a,b – are the vectors of the coefficients of the polynomials that are being
multiplied.
Examples: solve f1(x) . f2(x)
122)( 23
1 −+−= xxxxf
3)( 2
2 += xxf
Division of Polynomials
A polynomial can be divided by another polynomial using the command deconv
command.
Syntax: [q,r] = deconv(u,v)
Where:q – is a vector with the coefficients of the quotient polynomial.
r – is a vector with the coefficients of the remainder polynomial.
u – is a vector with the coefficients of the numerator polynomial.
v – is a vector with coefficients of the denominator polynomial.
Example: a. Divide 2x3 + 9x
2 + 7x – 6 by x + 3
37
Derivative of Polynomials
k = polyder(p)
o derivative of a single polynomial, p. k is a vector with the coefficients of
the polynomial that is the derivative.
k = polyder(a,b)
o derivative of a product of two polynomials a and b.
[n,d] = polyder(u,v) –
o derivative of a quotient of two polynomials.
Curve fitting with Polynomials
Also known as regression analysis
A process of fitting a function to a set of data points.
Syntax: p = polyfit(x,y,n)
p – is the vector of the coefficients of the polynomial that fits the data.
x – is a vector with horizontal coordinate of the data points (independent
variable)
y – is a vector with the vertical coordinate of the data points.
n – is the degree of the polynomial
38
EXERCISES
Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
1. Solve the roots of the equation:
a. 3x2 + 8x + 5 = 0
b. 5x2 + 7x + 7 = 0
c. 5x3 + 7x
2 – 7x + 8 = 0
2. Find the polynomial expression given the following factors:
a. (x + 3) (x – 2) (x + 2) (x + 4)
b. (x + 2) (x – 7) (x + 1) (x + 2)
3. Expand using partial fraction expansion
)5)(2)(3(
23)(
−+−+
=sss
ssQ
4. Solve for the
a. roots of numerator,
b. polynomial form of the denominator
c. partial fraction expanded form of the given system functions
a. )2)(5)(2)(3(
223)(
23
−−+−+−+
=zzzz
zzzzH
b. 324
223)(
24
235
+−
+−+=
zz
zzzzH
39
5. Given a set of data points x and y, estimate three polynomial functions (2nd
degree, 3rd
degree and 4th
degree) that will best fit the data. Compute new set of y
data from the three functions and determine which of the three functions will give
the least norm difference.
norm = 22
3
2
2
2
1 ... nvvvv ++++ where nnn yyv new−=
x = [0.9, 1.5, 3, 4, 6, 8, 9.5]
y = [0.9, 1.5, 2.5, 5.1, 4.5, 4.9, 6.3]
40
Experiment No. 9: MATLAB® GUI Part 1
OBJECTIVES
1. Become familiar with the basic graphic user interface commands and operation of
MATLAB.
2. Build basic MATLAB-based graphic user interface.
INTRODUCTION
Graphic User Interface – GUI
A graphical user interface is a pictorial interface to a program.
Advantages of using GUI
1. It makes things simple for the end users.
2. Users would not have to work from the command line interface.
3. Makes a program easy to understand.
Properties of a good GUI
1. Must be user friendly and easy to use.
2. Should behave in an understandable and predictable manner.
3. Must be simple and neat.
4. Must be functionally accurate.
Three principal elements required to create a MATLAB GUI
1. Components – Items in MATLAB GUI like push buttons, labels, edit boxes, etc. is a
graphical component.
There are four types of components;
a. Graphical controls – push buttons, edit boxes, sliders etc. Created by function
‘uicontrol’.
b. Static elements – text strings, frames. Created by function ‘uicontrol’.
c. Menus – created by function ‘uimenu’ and ‘uicontextmenu’.
d. Axes – used to display graphical data. Created by function ‘axes’.
2. Figures – A window in the computer screen where all components of the GUI must
be arranged.
41
3. Callbacks – Code executed in response to an event such as mouse click or a key
press.
Basic GUI Components (figure 9.1)
Graphical controls
1. Pushbutton – triggers a callback when clicked by a mouse.
2. Toggle button – either on or off, it changes state each time it is clicked, each
click triggers a callback.
3. Radio button – a type of toggle button that appears as a small circle with a dot, a
group of radio buttons are used to implement mutually exclusive
choices. Each click triggers a callback.
4. Check box – a type of toggle button that appears as a small box with a check
mark. Each click triggers a callback.
5. Edit box – displays a text string and allows the user to modify the information
displayed. A callback is triggered when the user presses the
Enter key.
6. List box – displays a series of text strings which a user can select one of the text
strings. A callback is triggered when the user selects a string.
7. Pop-up menu – displays a series of text strings in response to a mouse click.
When a pop-up menu is not clicked on, only the currently
selected string is visible.
42
8. Slider – adjusts a value in a smooth, continuous fashion by dragging the control
with a mouse. Each slider change triggers a callback.
Figure 9.1
Static elements
1. Frame – creates a frame, a rectangular box within a figure. Used to group sets of
controls together. Never triggers callbacks.
2. Text Field – creates a label, a text string located at a point on the figure. Never
triggers callbacks.
Menus and Axes
1. Menu items – creates menu item. Trigger callback when a mouse button is
release over them.
43
2. Context menus – creates a context menu, which appears over a graphical object
when a user right-click the mouse on that object.
3. Axes – creates a new set of axes to display data on. Never triggers callbacks.
GUI Development Environment
MATLAB GUI are created using the GUI Development Environment or simply
called ‘guide’, see figure 9.2. In using ‘guide’, MATLAB allows the programmer
to do the following;
1. Layout the GUI.
2. Select and align GUI components.
3. Edit GUI components’ properties.
4. Create a working program to implement the behavior of the GUI, referred to as the
GUI M-File.
Figure 9.2
GUI M-File
After laying out your GUI, you can program the GUI M-file using the M-file
editor. GUIDE automatically generates this file from your layout the first time
you save or run the GUI.
The GUI M-file does the following;
44
1. Initializes the GUI.
2. Contains code to perform tasks before the GUI appears on the screen,
such as creating data or graphics.
3. Contains the callback functions that are executed each time a user
clicks a GUI component.
Steps in creating GUI
1. Decide what elements are required by the GUI, what the function of each element
will be.
2. Type ‘guide’ in the MATLAB command window.
3. Visually design the GUI interface.
4. Use the GUI Development Environment tool Property Inspector to give each
component a name and to set characteristics of each component such as color, text
display and so on.
5. Save the figure to a file. When the figure is saved, two files will be created on disk
with the same name but different extensions. The .fig contains the actual GUI and the
M-file contains the code.
6. Add the code to implement the behavior associated with each callback function.
Figure 9.3
45
Figure 9.4
Properties for GUI Components
Name Property – The value of a figure's ‘Name’ property is the title that displays at the
top of the GUI. The first time you save or run the GUI, GUIDE sets the value of Name to
the name of the FIG-file. Once the GUI is saved, you can set the value of Name to the
string you want to use as its title. In the field next to Name, type Simple GUI, as shown in
the following figure.
Figure 9.5
Title Property – A panel's ‘Title’ property controls the title that appears at the top or
bottom of the panel. Select the panel in the Layout Editor and then scroll down in the
Property Inspector until you come to Title. In the field to the right of Title, change Panel
to Plot Types. Use the ‘TitlePosition’ property to control the position of the title.
46
Figure 9.6
String Property – You can set the label in some user interface controls, such as push
buttons and static text, by using the ‘String’ property. For example, to set the label of the
top push button, select the push button in the Layout Editor and then, in the Property
Inspector, scroll down until you come to String. In the field to the right of String, change
Push Button to Surf, as shown in the following figure.
Figure 9.7
Tag Property – The Tag property provides a string as a unique identifier for each
component. GUIDE uses this identifier to construct unique callback names for the
different components in the GUI. When you first add a component to a layout, GUIDE
sets the value of Tag to a default string such as pushbutton1. If the component has a
Callback property, GUIDE also sets the value of Callback to the string %automatic.
47
Figure 9.8
The GUI M-File Editing
In the GUI M-File you add code to the callbacks for the three push buttons and the pop-
up menu. Once GUIDE has created the M-file, you can open it in the MATLAB editor by
clicking the M-file Editor icon on the toolbar. In the editor, you can move the cursor to a
specific callback by clicking the function icon on the toolbar, then selecting the callback
you want in the pop-up menu that displays.
Figure 9.9
48
For example, clicking MyFirstGUI_OpeningFcn moves the cursor to the opening
function. The next topic explains how you can add code to the opening function to create
data for the GUI or perform other tasks.
SAMPLE PROGRAM
1. Type ‘guide’ in the command line interface.
2. Layout the components in the GUI similar to figure 9.3 in order to achieve GUI in
figure 9.4.
3. Edit the properties of the components using ‘Properties Inspector’ and follow the
settings as given below;
Pushbutton
String Click Here
Tag MyFirstButton
Static Text
String Total Clicks: 0
Tag MyFirstText
Figure Name My First GUI
4. Save as ‘MyFirstGUI’. MyFirstGUI.m and MyFirstGUI.fig will be created.
5. Go back to the command user interface, type ‘MyFirstGUI’ then enter.
6. Open MyFirstGUI.m.
7. Implement callback function to ‘MyFirstButton’. By adding the code below.
49
Figure 9.10
Figure 9.10
EXERCISES
1. Improve MyFirstGUI, such that there will be two buttons, ADD and MINUS. The
ADD button when clicked will add 1; while the Subtract button when clicked will
subtract 1 from its current count value.
2. Add a Toggle Button to MyFirstGUI, such that the ADD and SUBTRACT buttons
can now be enabled and disabled.
3. Change the appearance of MyFirstGUI by changing its color, size, font and visual
settings.
50
Experiment No. 10: MATLAB® GUI Part 2
OBJECTIVES
1. Become familiar with the other graphic user interface commands and operation of
MATLAB.
2. Build basic calculator using graphic user interface.
INTRODUCTION
In this experiment you will be ask to create your own basic Calculator using MATLAD
graphic user interface development environment. The calculator must be similar to figure
10.1
Figure 10.1
Figure 10.2
51
In order to achieve proper vertical and horizontal alignment, you can use the Align
Objects tool. You can assign the proper alignment horizontally and vertically with
different types of distribution.
The MyFirstCalc.m code
Figure 10.3
52
In figure 10.3 you can verify that the Tag used for each push button as they
correspond to each callback. The other property settings are in table 10.1.
Table 10.1: Property Settings
Pushbuttons
String Number or Math Operator Symbol
Tag Button*
Static Text
String *No change
Tag text1
Background Color White (or your choice of
background color)
Foreground Color Black (or your choice of font color)
Font Size 30
Horizontal Alignment Right
Figure Name My First Calc
Callback code for every pushbutton except the = (equals)
Figure 10.4
53
Callback code for the equal sign
Figure 10.5
After coding the callbacks for pushbuttons
The code for each pushbutton callback except the equals button is in figure 10.4, you
must edit it correspondingly to every pushbutton digit including the /, *, - and + operator
symbols. Figure 10.5 shows the one for the equals button callback. After completion, run
the GUI and you will be able to display numbers to the static textbox as shown in figure
10.6.
Figure 10.6
54
EXERCISES
1. Construct a basic calculator using MATLAB graphic user interface development
environment, using the settings indicated in the steps above.
2. Customize the calculator by adding a decimal point and clear button.
3. Add more pushbuttons such as (, ), sin, cos and tan, then create a callbacks for
each pushbuttons. Verify the operation of the calculator.