Technical Computing Laboratory Manual
Technical Computing Laboratory Manual
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.
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.
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
inf
Same as i.
NaN
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.
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
Addition
Subtraction
Multiplication
Division
Power (exponentiation)
( )
>> b = 1;
>> y = a^2+(b/3)-1
Description
Example
>> sin(pi/6)
ans = 0.5000
radians).
cos(x) Cosine of angle x (x in
>> cos(pi/6)
ans = 0.8660
radians).
radians).
in radians).
Function
sqrt(x)
Description
Example
Square root.
>> sqrt(81)
ans = 9
exp(x)
Exponential (ex).
>> exp(5)
ans = 148.4132
abs(x)
Absolute value.
>> abs(-24)
ans = 24
log(x)
log10(x)
Natural logarithm.
>> log(1000)
ans = 6.9078
Base 10 logarithm.
>> log10(1000)
ans = 3.0000
factorial(x)
>> factorial(5)
Display Format
Command
format short
Description
Example
digits
41.4286
format long
digits
41.42857142857143
format short e
decimal digits.
4.1429e+001
format long e
decimal digits.
4.142857142857143e+001
format rat
>> 290/7
Rational form
ans = 290/7
EXERCISES
1.
12 + 15
(3)(3)
2. 16 +
3. 1 +
4.
1
1 1
+
8 4
sin 30 o + cos 25 o
tan 30 o
5
5.
44
4
11
456 + 3 323
cos 80 o
1. V =
4
R3 ,
3
2. y = ln(e 2 x +3 + x) ,
3.
for R = 2 meters
for x = 1.5
sin ( / 3) + cos( / 4)
in rational form
tan( / 6)
Experiment No. 2:
OBJECTIVES
INTRODUCTION
x = 1 2 3
1
y =2
3
>> x1 = [0:2:10]
>> y1 = [0:2:10]
>> x2 = linspace(0,10,5)
>> y2 = linspace(0,10,5)
>> A = [1 2 3; 4 5 6; 7 8 9]
1 2 3
A = 4 5 6
7 8 9
eye (n)
DESCRIPTION
ones (m,n)
rand (m,n)
zeros(m,n)
randn(m,n)
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]
1 2 3
E= 4 5 6
7 8 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
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];
>> C = A + B
>> D = A B
3. Multiplication of Vectors
4. Multiplication of Matrix
5.
Transpose of a Matrix
6. Array Operations
Element-by-element operations
>> a = [1 2 3];
>> b = [1 2 3];
a. Multiplication
>> c = a.*b
10
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.
xy +
z=
( x + y)
y
x
( yx)
+ 10 x / y
Create matrix C:
2 4 6 8 10
C = 3 6 9 12 15
7 14 21 28 35
11
Matrix X
1 6 2
3 9 6
4 0 3
Matrix Y
1 9 4
2 0 5
1 7 3
Matrix Z
3 7 4
2 3 1
9 2 5
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.
12
Experiment No. 3
SCRIPT FILES
OBJECTIVES
INTRODUCTION
SCRIPT FILES
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
13
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)
Output Commands
The disp() command
or
disp(text as string)
Where:
text.
14
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=
1 2
r h
3
S = r r 2 + h 2
3. Write a script file that will compute the sin of an angle using the Taylor series
formula: sin x =
(1) k x 2 k +1
The program will prompt the user to input the
k = 0 ( 2 k + 1)!
n
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
15
Experiment No. 4
FUNCTION FILES
OBJECTIVES
INTRODUCTION
FUNCTION FILES
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:
16
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
3. Function Body
Local Variables
Variables inside a function file and do not recognize in the command window.
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.
17
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)
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=
1 2
r h
3
S = r r 2 + h 2
3. The function sin(x) can be written as a Taylor series expanded form i.e.:
( 1) k x 2 k +1
sin x =
Write a user defined function file that calculates sin(x)
k = 0 ( 2 k + 1)!
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).
18
Experiment No. 5:
MATLAB PROGRAMMING
OBJECTIVE
INTRODUCTION
PROGRAMMING in MATLAB
Relational Operators
Relational Operator
Description
<
Less than
>
Greater than
<=
>=
= =
Equal to
~ =
Not equal to
Logical Operators
Logical Operator
Description
&
AND
OR
NOT
xor(A,B)
Exclusive or
19
Order of Precedence
Precedence
Operation
1 (highest)
Parentheses ( )
Exponentiation
Multiplication, Division
Addition, Subtraction
Relational Operators
8 (lowest)
Logical OR ( | )
Function
Description
and(A,B)
Equivalent to A & B
or(A,B)
Equivalent to A | B
not(A)
Equivalent to ~ A
xor(A,B)
all(A)
any(A)
find(A)
find(A>b)
20
Logical Operators
INPUT
OUTPUT
AND
OR
XOR
NOT A
NOT B
Conditional Statements
1. The if-end Structure
3. The if-elseif-else-end Structure
if conditional expression
if conditional expression 1
command 1
command 2
command 1
command 2
command n
end
command n
elseif conditional
expression2
command 1
command 2
if conditional expression
command 1
command 2
command n
else
command 1
command n
command 2
else
command 1
command 2
command n
end
command n
end
21
Provides a means for choosing one group of commands for execution out of
several possible groups.
switch switch expression
command 1
case value 1
:
command n
command 1
:
otherwise%optional
command n
case value 2
command 1
:
command 1
command n
end
command n
case value 3
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
22
2. while-end Loop
end
23
EXERCISES
1. Write a program in a script file that determines the real roots of a quadratic
equation ax 2 + bx + c = 0 . 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:
D = b 2 4ac
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. 2 x 2 + 8 x 3 = 0
b. 15 x 2 + 10 x + 5 = 0
c. 18 x 2 + 12 x + 2 = 0
2. The function f ( x) = e x can be represented in a Taylor series by:
xn
e =
Write a program in a script file that determines ex by using the
n = 0 n!
x
24
Experiment No. 6:
OBJECTIVES
INTRODUCTION
1. Plot
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
-.
25
Line Color
Specifier
Red
Green
Blue (default)
Cyan
Magenta
Yellow
Black
White
Marker Type
Plus sign
Circle
Asterisk
Point
Square
Diamond
Five-pointed star
Six-pointed star
Property Name
linewidth
markersize
Specifier
Description
Property Value
line
(default 0.5)
marker
26
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
2. hold on - it retains the current plot and its properties and allows the user
27
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
14. pie(x) pie plot, where x is a row vector which specifies the division of
pie.
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
28
EXERCISES
Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
1. Plot the function f ( x) =
x2 x +1
for 10 < x < 10
x2 + x +1
2. Plot the following functions using polar plot in a single plot using the following
conditions
a. r = 1 + 2 sin , for 0 < < 6 . Use red dash-dot line for the plot.
b. r = 1 2 sin , for 0 < < 6 . Use black solid line for the plot.
c. r = 1 + 2 cos , for 0 < < 6 . Use green dash-dot line for the plot.
d. r = 1 2 cos , for 0 < < 6 . Use yellow solid line for the plot.
4. Given the function y = e 10 x for 0 < x < 20 , compare the graphs using the
function plot() and using log scale plot.
29
Experiment No. 7:
OBJECTIVE
INTRODUCTION
3-D Line-Plot
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)
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.
30
Steps:
1. Creating a grid in the x-y plane
[X,Y] = meshgrid(x,y)
X,Y are matrices with the coordinates of the grid and Z is a matrix with
meshc(X,Y,Z)
surfc(X,Y,Z)
surfl(X,Y,Z)
waterfall(X,Y,Z)
only
31
contour3(X,Y,Z,n)
levels (optional)
2-D contour plot n is the number of contour
contour(X,Y,Z,n)
levels (optional)
EXERCISES
Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
x2 + y2
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 5 < t < 5
x = e at sin w t
y = e at cos w t
z = e bt
32
Compare all the generated graphs from one to another and explain the effects
of changing a, b, and w
33
Experiment No. 8:
POLYNOMIAL OPERATIONS
OBJECTIVE
INTRODUCTION
Polynomials
Polynomials are functions that have the form:
f ( x ) = a n x n + a n 1 x n 1 + .... + a 1 x + a 0
Examples are:
X ( z) = 5z 5 + 6z 2 + 7 z + 3
H ( z ) = 2 z 2 4 z + 10
Useful Commands:
34
functions where
o u numerator polynomial
o v denominator polynomial
o q quotient polynomial
o r remainder polynomial
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
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)
35
Multiplication of Polynomials
Syntax:
c = conv(a,b)
the multiplication.
a,b are the vectors of the coefficients of the polynomials that are being
multiplied.
Division of Polynomials
Example:
36
Derivative of Polynomials
k = polyder(p)
k = polyder(a,b)
[n,d] = polyder(u,v)
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
37
EXERCISES
Answer or simulate the following problems. Write the command that you used and draw
all the graphs generated:
a. (x + 3) (x 2) (x + 2) (x + 4)
b. (x + 2) (x 7) (x + 1) (x + 2)
Q( s) =
3s + 2
( s 3)( s + 2)( s 5)
a. H ( z ) =
3z 3 + 2 z 2 z + 2
( z 3)( z + 2)( z 5)( z 2)
b. H ( z ) =
3z 5 + 2 z 3 z 2 + 2
4z 4 2z 2 + 3
38
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 =
v1 + v 2 + v3 + ... + v n
2
39
where v n = y n y new n
Experiment No. 9:
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
2. Figures A window in the computer screen where all components of the GUI must
be arranged.
40
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.
41
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.
42
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.
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;
43
Figure 9.3
44
Figure 9.4
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.
45
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.
46
Figure 9.8
Figure 9.9
47
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;
String
Click Here
Tag
MyFirstButton
String
Total Clicks: 0
Tag
MyFirstText
Name
My First GUI
Pushbutton
Static Text
Figure
48
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.
49
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
50
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.
Figure 10.3
51
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.
String
Tag
Button*
String
*No change
Tag
text1
Pushbuttons
Background Color
Static Text
Figure
Foreground Color
Font Size
30
Horizontal Alignment
Right
Name
My First Calc
Figure 10.4
52
Figure 10.5
Figure 10.6
53
EXERCISES
3. Add more pushbuttons such as (, ), sin, cos and tan, then create a callbacks for
each pushbuttons. Verify the operation of the calculator.
54