Professional Documents
Culture Documents
Lab Manual EE3001
Lab Manual EE3001
Lab Manual EE3001
ENGINEERING
COMPUTATIONAL
METHODS LAB MANUAL
Prepared by
Dr. Esam Yosry
May 2014
1. Preface III
2. Laboratory Procedures IV
14. References 44
Eng. Computational Methods Lab Electrical Engineering Dept.
PREFACE
Although each Lab Work contains some reading materials, the manual is not self-contained in
theory. Each Lab Work is designed to be completed in a three-hour laboratory period
provided that you come well prepared. Before coming to the Lab, you are expected to have
read and clearly understood the algorithm to be performed, completed the required pre-lab
work, and reviewed the method related to the algorithm.
There are 11 Lab Works in this manual. Although each Lab Work includes one or more
topics introduced in the Engineering Computational Methods course, the first four Work Labs
are primarily used to familiarize you with basics of MATLAB.
You will experience, and hopefully enjoy, the progression and challenge represented by the
Lab Work in the manual. Undoubtedly, you'll feel frustrated sometimes when nothing seems
to work; but that is exactly what gives you the thrill when you succeed. It is okay if you make
a mistake but make sure that you do not commit the same error again. "Stupid mistakes" are
usually made when you work in a hasty, sloppy manner. It always pays to do your code
writing carefully and systematically.
Due to the limited number of computers available in the laboratory, you will be divided into
two- or three-person teams. Each team will be assigned to and will be responsible for
computer. Try to develop a good working relationship with your lab partners as you will be
working with them throughout the entire semester. It is suggested that each person in the
team serves as the team leader on a rotating basis. The team leader is responsible for
coordinating the activities and ensuring the success of the Lab Work.
Each student should maintain a laboratory notebook. The bounded lab notebook is used to
record all pertinent information related to the Lab Work such as observations and remarks.
Lab notebooks are important documents used in professional matters such as validation,
patent, and investigation. Your lab instructor will periodically inspect your notebook as a part
of your grade. Each student is required to submit a lab report per Lab Work.
Laboratory Procedures
To discuss and become aware of laboratory procedures and requirements.
D. Pre-Lab Report
Read the descriptions of the formal Pre-lab report in appendix A. of this manual. You must
follow the designated format. Pre-lab report should be generated by a word processor also
graphs and diagrams should be computer generated. The pre-lab report must include:
1. Header and Footer Information: 1 point.
2. Introduction: 2 points.
3. Algorithm: 1 point.
4. MATLAB code: 2 points.
5. Summary: 1 point.
6. Answers to Pre-lab questions: 2 points.
7. Pre-lab Report Checklist: 1 point.
Total points: 10 points.
E. Lab Notebook
The lab notebook is a complete record of ALL work pertaining to the Lab Work. It is not
necessary to include lengthy explanations and procedures in the notebook, but the entries
must be sufficient for another person to understand your methods and replicate the Lab
Work.
The pages of the lab notebook must be bound (not loose leaf or spiral) and should be
numbered consecutively. The lab notebook entries must be in ink, and no pages should be left
blank between entries. Begin the entries for each Lab Work on a new page, giving the title of
the Lab Work and the date. In case some of the data or calculations written in the notebook
turn out to be in error, do not tear out the page or completely obliterate the entries: a single
line through the error is preferred. This way there is no question regarding the legitimacy and
completeness of the notebook material. Furthermore, you will not be penalized for having
lined-out errors and corrections in your notebook.
Read the descriptions of the formal lab notebook in appendix A. of this manual. You must
follow the designated format. Lab notebook should be written by hand.
The lab notebook should contain:
1. Lab Work #, title, student name and ID, and date: 1 point.
2. Outline: 2 points.
3. Algorithm: 4 points.
4. Expected results by hand calculations: 2 points.
5. MATLAB code: 5 points.
6. Graphs: 2 points
sketch graphs of the results.
7. Comparison: 3 points
comparing hand calculations and results.
8. Evaluation Table: 1 point.
Total points: 20 points.
F. Lab Report
The report should be written specifically to meet the needs of the reader, meaning that the
writing must be brief, interesting, and complete. Students should generate lab report in a
professional manner. Read the descriptions of the formal lab report in appendix A of this
manual and you must follow the designated format. Lab report should be generated by a word
processor also graphs and diagrams should be computer generated. The report must include:
1. Cover page: 2 points.
2. Objectives: 2 points.
3. Algorithm: 5 points.
4. Data presentations: 5 points.
5. MATLAB code: 15 points.
6. Conclusion: 2 points.
7. Answers to lab review questions: 5 points.
8. References: 1 point.
9. Appendices: 1 point.
10. Lab Report Checklist: 2 points.
11. Pre-Lab Report and a photocopy of Lab Notebook must be attached with signature.
No credit of Lab Report without both.
Total points: 40 points.
G. Lab Regulations
To assure smooth running of the laboratory, the following rules must be observed by all
students. Violations of these rules will result in penalties.
1) Each student must attend all lab sessions.
2) Notify the instructor immediately for any damaged or malfunctioning computer.
3) Laboratory must be kept clean. No eating, drinking, or smoking in the lab.
4) Always come to the lab well prepared. Pre-lab work must be completed before coming.
5) Students will work in teams. Please have your teammate selected before Lab Work #1. If
you cannot find a teammate, ask your Lab Instructor for a partner assignment.
6) Two copies for pre-lab reports are required (one for Lab Instructor at the beginning of
the lab period and one for student attached in lab notebook).
7) Lab instructor will grade your pre-lab report during the lab and return it before leaving.
8) Observe all safety rules and understand them for your safety.
9) No horseplay in the lab.
10) Lab instructor will grade your Lab notebook when Lab Work is completed and before
you leave the lab.
11) Turn off the computer.
12) Lab reports are always due the next session after the lab is completed.
13) Late lab reports will incur a 20 points per week penalty.
14) Lab reports must be completed independently. You can share only the collected data sets
with your team. Copying any part of the report from others is strictly prohibited.
15) Students are encouraged to discuss laboratory assignments with classmates.
16) Always bring this manual with you to lab. for reference.
H. Plagiarism
You are expected to behave professionally and ethically. You will be treated as an engineer.
It is expected that lab partners will have the same data and similar organizations for their lab
reports. Identical Procedures and Conclusions are NOT acceptable. Any work which appears
to be Cloned, or otherwise overly-similar to another’s work will be assumed to be
plagiarized. Plagiarism is a form of cheating or fraud.
Lab Work #1
Introduction to MATLAB
OBJECTIVES
1. Become familiar with the use of MATLAB.
2. Become familiar with the Command Window and MATLAB Desktop.
3. Become familiar with numbers and arithmetic operations, saving and reloading a work, using
help, MATLAB demos, interrupting a running program and long command lines.
BACKGROUND
The purpose of this Lab Work is to present basics of MATLAB. We do not assume
any prior knowledge. MATLAB is a high-performance 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.
The name MATLAB stands for matrix laboratory. In university environments, it is the
standard instructional tool for introductory and advanced courses in mathematics,
engineering, and science. MATLAB features a family of add-on application-specific
solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you
to learn and apply specialized technology. The MATLAB main window is shown in
Fig.1.1.
The Command Window is one of the main tools you use to enter data, run MATLAB
functions and other M-files, and display results.
Graphics MATLAB has extensive facilities for displaying vectors and matrices as graphs, as
well as annotating and printing these graphs. It includes high-level functions for two-
dimensional and three-dimensional data visualization, image processing, animation, and
presentation graphics.
In MATLAB, a matrix is a rectangular array of numbers. Like most other programming
languages, MATLAB provides mathematical expressions, but unlike most programming
languages, these expressions involve entire matrices. The building blocks of expressions are
Variables Numbers Operators Functions
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1. MATLAB is a high-performance language for technical computing.
2. The name MATLAB stands for max laboratory.
PROCEDURE
1- The Command Window
You can start MATLAB by double clicking on the MATLAB icon that should be on the
desktop of your computer. This brings up the window called the Command Window. This
window allows a user to enter simple commands. To clear the Command Window type clc
and press the Enter key. To perform a simple computations type a command and press the
Enter key. For instance,
s = 1 + 2
s =
3
fun = sin(pi/4)
fun =
0.7071
In the second example the trigonometric function sine and the constant pi are used. In
MATLAB they are named sin and pi, respectively. Note that the results of these
computations are saved in variables whose names are chosen by the user. If they will be
needed during your current MATLAB session, then you can obtain their values typing their
names and pressing the Enter. For instance,
s
s =
3
Variable name begins with a letter, followed by letters, numbers or underscores. MATLAB
recognizes only the first 31 characters of a variable name.
To change a format of numbers displayed in the Command Window you can use one of the
several formats that are available in MATLAB. The default format is called short (four digits
after the decimal point.) In order to display more digits click on File, select Preferences, and
next select a format you wish to use. They are listed below the Numeric Format. Next click
on Apply and OK and close the current window. You can also select a new format from
within the Command Window. For instance, the following command format long changes a
current format to the format long. To display more digits of the variable fun type
fun
fun =
0.70710678118655
To close MATLAB type exit in the Command Window and next press Enter. A second way
to close your current MATLAB session is to select File in the MATLAB's toolbar and next
click on Exit MATLAB option. All unsaved information residing in the MATLAB
Workspace will be lost.
xi = 10
xi =
10
xr = 10.01
xr =
10.0100
is saved as the real number. It is not our intention to discuss here machine representation of
numbers. This topic is usually included in the numerical analysis courses. Variables realmin
and realmax denote the smallest and the largest positive real numbers in MATLAB. For
instance,
realmin
ans =
2.2251e-308
Complex numbers in MATLAB are represented in rectangular form. The imaginary unit -1 is
denoted either by i or j
i
ans =
0 + 1.0000i
Operation Symbol
addition +
subtraction -
multiplication *
division / or \
exponentiation ^
MATLAB has two division operators / - the right division and \ - the left division. They do
not produce the same results
rd = 47/3
rd =
15.6667
ld = 47\3
ld =
0.0638
whos
Name Size Bytes Class
ans 1x1 16 double array (complex)
fun 1x1 8 double array
ld 1x1 8 double array
rd 1x1 8 double array
s 1x1 8 double array
xi 1x1 8 double array
xr 1x1 8 double array
Grand total is 7 elements using 64 bytes
Shows all variables used in current session. You can also use command who to generate a list
of variables used in current session.
who
Your variables are:
ans ld s xr
fun rd xi
To save your current workspace select Save Workspace as from the File menu. Chose a
name for your file, e.g. filename.mat and next click on Save. Remember that the file you just
created must be located in MATLAB's search path. Another way of saving your workspace is
to type save filename in the Command Window. The following command save filename s
saves only the variable s.
Another way to save your workspace is to type the command diary filename in the
Command Window. All commands and variables created from now will be saved in your
file. The following command: diary off will close the file and save it as the text file. You can
open this file in a text editor, by double clicking on the name of your file, and modify its
contents if you wish to do so.
To load contents of the file named filename into MATLAB's workspace type load filename
in the Command Window.
More advanced computations often require execution of several lines of computer code.
Rather than typing those commands in the Command Window you should create a file. Each
time you will need to repeat computations just invoke your file. Another advantage of using
files is the ease to modify its contents.
4- Help
One of the nice features of MATLAB is its help system. To learn more about a function you
are to use, say rref, type in the Command Window, as shown in Fig.1.2.
help svd
SVD Singular value decomposition.
[U,S,V] = SVD(X) produces a diagonal matrix S, of the same
dimension as X and with nonnegative diagonal elements in
decreasing order, and unitary matrices U and V so that
X = U*S*V'.
S = SVD(X) returns a vector containing the singular values.
[U,S,V] = SVD(X,0) produces the "economy size"
decomposition. If X is m-by-n with m > n, then only the
first n columns of U are computed and S is n-by-n.
See also SVDS, GSVD.
Overloaded methods
help sym/svd.m
If you do not remember the exact name of a function you want to learn more about use
command lookfor followed by the incomplete name of a function in the Command
Window. In the following example we use a "word" sv
lookfor sv
ISVMS True for the VMS version of MATLAB.
HSV2RGB Convert hue-saturation-value colors to red-green-blue.
RGB2HSV Convert red-green-blue colors to hue-saturation-value.
GSVD Generalized Singular Value Decomposition.
SVD Singular value decomposition.
SVDS Find a few singular values and vectors.
HSV Hue-saturation-value color map.
JET Variant of HSV.
CSVREAD Read a comma separated value file.
CSVWRITE Write a comma separated value file.
ISVARNAME Check for a valid variable name.
RANDSVD Random matrix with pre-assigned singular values.
Trusvibs.m: % Example: trusvibs
SVD Symbolic singular value decomposition.
RANDSVD Random matrix with pre-assigned singular values.
The helpwin command, invoked without arguments, opens a new window on the screen. To
find an information you need double click on the name of the subdirectory and next double
click on a function to see the help text for that function. You can go directly to the help text
helpwin zeros
ZEROS Zeros array.
ZEROS(N) is an N-by-N matrix of zeros.
ZEROS(M,N) or ZEROS([M,N]) is an M-by-N matrix of zeros.
ZEROS(M,N,P,...) or ZEROS([M N P ...]) is an M-by-N-by-P-by-...
array of zeros.
ZEROS(SIZE(A)) is the same size as A and all zeros.
See also ONES.
generates an information about MATLAB's function zeros. MATLAB also provides the
browser-based help. In order to access these help files click on Help and next select Help
Desk (HTML). This will launch your Web browser. To access an information you need click
on a highlighted link or type a name of a function in the text box. In order for the Help Desk
to work properly on your computer the appropriate help files, in the HTML or PDF format,
must be installed on your computer. You should be aware that these files require a significant
amount of the disk space.
5- Demos
To learn more about MATLAB capabilities you can execute the demo command in the
Command Window or click on Help and next select Examples and Demos from the pull-
down menu. Some of the MATLAB demos use both the Command and the Figure windows.
To learn about matrices in MATLAB open the demo window using one of the methods
described above. In the left pane select Matrices and in the right pane select Basic matrix
operations then click on Run Basic matrix Click on the Start >> button to begin the show.
If you are familiar with functions of a complex variable I recommend another demo. Select
Visualization and next 3-D Plots of complex functions. You can generate graphs of simple
power functions by selecting an appropriate button in the current window.
You can suppress output to the screen by adding a semicolon after the statement
u = 2 + 3;
Lab Work #2
MATLAB Basics-I
OBJECTIVES
Become familiar with m-files.
BACKGROUND
1- The m-files
Files that contain a computer code are called the m-files. There are two kinds of m-files: the
script files and the function files. Script files do not take the input arguments or return the
output arguments. The function files may take input arguments or return output arguments.
To make the m-file click on File next select New and click on M-File from the pull-down
menu. You will be presented with the MATLAB Editor/Debugger screen. Here you will
type your code, can make changes, etc. Once you are done with typing, click on File, in the
MATLAB Editor/Debugger screen and select Save As… . Chose a name for your file,
e.g., firstgraph.m and click on Save. Make sure that your file is saved in the directory that
is in MATLAB's search path.
If you have at least two files with duplicated names, then the one that occurs first in
MATLAB's search path will be executed. To open the m-file from within the Command
Window type edit firstgraph and then press Enter or Return key.
f = inline('sqrt(x.^2+y.^2)','x','y')
f =
Inline function:
f(x,y) = sqrt(x.^2+y.^2)
f(3,4)
ans =
5
A = [1 2;3 4]
A =
1 2
3 4
and
B = ones(2)
B =
1 1
1 1
Then
C = f(A, B)
C =
1.4142 2.2361
3.1623 4.1231
For the later use let us mention briefly a concept of the string in MATLAB. The character
string is a text surrounded by single quotes. For instance,
str =
programming in MATLAB is fun
In the previous section you have learned how to create the function files. Some functions
take as the input argument a name of another function, which is specified as a string. In
order to execute function specified by string you should use the command feval as shown
below
Consider the problem of computing the least common multiple of two integers. MATLAB
has a built-in function lcm that computes the number in question. Recall that the least
common multiple and the greatest common divisor (gcd) satisfy the following equation
ab = lcm(a, b)gcd(a,b)
MATLAB has its own function, named gcd, for computing the greatest common divisor.
To illustrate the use of the command feval let us take a closer look at the code in the m-file
mylcm
function c = mylcm(a, b)
% The least common multiple c of two integers a and b.
if feval('isint',a) & feval('isint',b)
c = a.*b./gcd(a,b);
else
error('Input arguments must be integral numbers')
end
Command feval checks whether or not both input arguments are integers. If this condition is
satisfied, then the least common multiple is computed using the formula mentioned earlier,
otherwise the error message is generated. Note use of the command error, which takes as
the argument a string. Function that is executed twice in the body of the function mylcm is
named isint
function k = isint(x);
% Check whether or not x is an integer number.
% If it is, function isint returns 1 otherwise it returns 0.
format long
realmin
ans =
2.225073858507201e-308
format short
--------------------------------------------------------------------------------------------------
function y = corrtrap(fname, fpname, a, b)
% Corrected trapezoidal rule y.
% fname - the m-file used to evaluate the integrand,
% fpname - the m-file used to evaluate the first derivative
% of the integrand,
% a,b - endpoinds of the interval of integration.
h = b - a;
y = (h/2).*(feval(fname,a) + feval(fname,b))+ (h.^2)/12.*( ...
feval(fpname,a) - feval(fpname,b));
The input parameters a and b can be arrays of the same dimension. This is possible
because the dot operator proceeds certain arithmetic operations in the command that
defines the variable y. In this example we will integrate the sine function over two
intervals whose end points are stored in the arrays a and b, where
a = [0 0.1];
b = [pi/2 pi/2 + 0.1];
y = corrtrap('sin', 'cos', a, b)
y =
0.9910 1.0850
(b) 22×3
(c) 1.5×10−4+2.5×10−2
Q 5: Draw the graph of Cos(x) by using the values of x between 0 and 6×π and the increment
is 0.2. ( make it with red color.)
Q 6: Solve the following equations by using Matrix Method Approach (assume a third
equation from your mind):
x+y+z=1
x–y+z=0
Lab Work #3
MATLAB Basics-II
OBJECTIVES
1. Become familiar with the for, while loops.
2. Become familiar with the if-else-end, switch-case constructions.
3. Become familiar with Relations and logical operators.
4. Become familiar with Strings.
5. Become familiar with Cell arrays
6. Become familiar with Rounding to integers.
BACKGROUND
To control the flow of commands, the makers of MATLAB supplied four devices a
programmer can use while writing his computer code.
x =
Columns 1 through 7
0 0.3090 0.5878 0.8090 0.9511 1.0000 0.9511
Columns 8 through 11
0.8090 0.5878 0.3090 0.0000
H =
1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
0.3333 0.2500 0.2000 0.1667 0.1429
0.2500 0.2000 0.1667 0.1429 0.1250
0.2000 0.1667 0.1429 0.1250 0.1111
Consider the following problem. Generate a 10-by-10 matrix A = [akl], where akl =
sin(k)cos(l). Using nested loops one can compute entries of the matrix A using the
following code
A = zeros(10);
for k=1:10
for l=1:10
A(k,l) = sin(k)*cos(l);
end
end
k = 1:10;
A = sin(k)'*cos(k);
q = pi;
while q > 0.01
q = q/2;
end
q =
0.0061
if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end
---------------------------------------------------------------------------------------------------
function T = ChebT(n)
% Coefficients T of the nth Chebyshev polynomial of the first kind.
% They are stored in the descending order of powers.
t0 = 1;
t1 = [1 0];
if n == 0
T = t0;
elseif n == 1; T
= t1;
else
for k=2:n
T = [2*t1 0] - [0 0 t0];
t0 = t1;
t1 = T;
end
end
In the following example a random integer number x from the set {1, 2, … , 10} is
generated. If x = 1 or x = 2, then the message Probability = 20% is displayed to the screen.
If x = 3 or 4 or 5, then the message Probability = 30% is displayed, otherwise the message
Probability = 50% is generated. The script file fswitch utilizes a switch as a tool for
handling all cases mentioned above
% Script file fswitch.
x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10}
switch x
case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%');
otherwise
disp('Probability = 50%');
end
Operator Description
< Less than
<= Less than or equal to
> Greater
>= Greater or equal to
== Equal to
~= Not equal to
Operator == compares two variables and returns ones when they are equal and zeros
otherwise.
a = [1 1 3 4 1]
a =
1 1 3 4 1
ind = (a == 1)
ind =1 1 0 0 1
This is an example of so-called logical addressing in MATLAB. You can obtain the
same result using function find
ind = find(a == 1)
ind =1 2 5
Suppose that one wants to select all entries x that satisfy the inequalities x > 1 or x < -0.2
where
x = randn(1,7)
x =
-0.4326 -1.6656 0.1253 0.2877 -1.1465 1.1909 1.1892
is the array of normally distributed random numbers. We can solve easily this problem
using operators discussed in this section
ind = (x >= 1) | (x < -0.2)
ind =1 1 0 0 1 1 1
y = x(ind)
y =
-0.4326 -1.6656 -1.1465 1.1909 1.1892
4- Strings
String is an array of characters. Each character is represented internally by its ASCII
value. This is an example of a string
str = 'I am learning MATLAB this semester.'
str =
I am learning MATLAB this semester.
iseq =
1
strcat(str,str2)
ans =
I am learning MATLAB this semester. I am learning MATLAB this semester.
Note that the concatenated strings are not separated by the blank space.
You can create two-dimensional array of strings. To this aim the cell array rather than the
two- dimensional array must be used. This is due to the fact that numeric array must have
the same number of columns in each row.
carr =
'first name'
'last name'
'hometown'
Note use of the curly braces instead of the square brackets. Cell arrays are discussed in
detail in the next section of this tutorial.
MATLAB has two functions to categorize characters: isletter and isspace. We will run
both functions on the string str
isletter(str)
ans =
Columns 1 through 12
1 0 1 1 0 1 1 1 1 1 1
1
Columns 13 through 24
1 0 1 1 1 1 1 1 0 1 1
1
Columns 25 through 35
1 0 1 1 1 1 1 1 1 1 0
5- Cell arrays
Two data types the cell arrays and structures make MATLAB a powerful tool for
applications. To create the cell array one can use one of the two techniques called the cell
indexing and the content indexing. The following example reveals differences between
these two techniques. Suppose one want to save the string 'John Brown' and his SSN 123-
45-6789 (without dashes) in the cell array.
1. Cell indexing
A(1,1) = {'John Brown'};
A(1,2) = {[1 2 3 4 5 6 7 8 9]};
2. Content indexing
B{1,1} = 'John Brown';
B{1,2} = [1 2 3 4 5 6 7 8 9];
A =
'John Brown' [1x9 double]
celldisp(A)
A{1} =
John Brown
A{2} =
1 2 3 4 5 6 7 8 9
To access data in a particular cell use content indexing on the right-hand side. For instance,
B{1,1}
ans =
John Brown
B =
[1x9 double]
This command
C = {A B}
C =
{1x2 cell} {1x1 cell}
C{1}{1} =
John Brown
C{1}{2} =
1 2 3 4 5 6 7 8 9
C{2}{1} =
1 2 3 4 5 6 7 8 9
6- Rounding to integers.
A full list of functions designed for rounding numbers is provided below
Function Description
floor Round towards minus infinity
ceil Round towards plus infinity
fix Round towards zero
round Round towards nearest integer
T =
1.1650 1.6961 -1.4462 -0.3600 -0.0449
0.6268 0.0591 -0.7012 -0.1356 -0.7989
0.0751 1.7971 1.2460 -1.3493 -0.7652
0.3516 0.2641 -0.6390 -1.2704 0.8617
-0.6965 0.8717 0.5774 0.9846 -0.0562
A = floor(T)
A =
1 1 -2 -1 -1
0 0 -1 -1 -1
0 1 1 -2 -1
0 0 -1 -2 0
-1 0 0 0 -1
B = ceil(T)
B =
2 2 -1 0 0
1 1 0 0 0
1 2 2 -1 0
1 1 0 -1 1
0 1 1 1 0
C = fix(T)
C =
1 1 -1 0 0
0 0 0 0 0
0 1 1 -1 0
0 0 0 -1 0
0 0 0 0 0
D = round(T)
D =
1 2 -1 0 0
1 0 -1 0 -1
0 2 1 -1 -1
0 0 -1 -1 1
-1 1 1 1 0
Q.2. write a complete program to make a decision of student’s mark with all grades from A to
F.
Q.3. Write a program to create a 5x5 matrix of (1/2)’s and diagonal are all 0.25.
Lab Work #4
MATLAB Graphics
OBJECTIVES
Become familiar with MATLAB graphics for 2-D and 3-D.
BACKGROUND
MATLAB has several high-level graphical routines. They allow a user to create
various graphical objects including two- and three-dimensional graphs, graphical user
interfaces (GUIs), movies, to mention the most important ones.
In the Command Window click on Help and select Examples and Demos. Chose
Visualization, and select 2-D Plots. You will be presented with several buttons. Select Line
and examine the m-file below the graph. It should give you some idea about computer code
needed for creating a simple graph. It is recommended that you examine carefully contents
of all m-files that generate the graphs in this demo.
PROCEDURE
Basic function used to create 2-D graphs is the plot function. This function takes a variable
number of input arguments. For the full definition of this function type help plot in the
Command Window.
------------------------------------------------------------------------------------------------------
% Script file graph5.
[x,y,z] = sphere(30);
surf(x+2, y-1, z+1)
x = 0:0.01:1;
plot(x, x.^2)
print
Lab Work #5
Root Finding
Biscetion Method
OBJECTIVES
In this Lab Work we consider one of the most basic problems of numerical
approximation, the root-finding problem. This process involves finding a root, or solution, of
an equation of the form f (x) = 0, for a given function f . A root of this equation is also called
a zero of the function f .
BACKGROUND
Suppose f is a continuous function defined on the interval [a, b], with f (a) and f (b)
of opposite sign. This implies that a number p exists in (a, b) with f ( p) = 0. Although the
procedure will work when there is more than one root in the interval (a, b), we assume for
simplicity that the root in this interval is unique. The method calls for a repeated halving (or
bisecting) of subintervals of [a, b] and, at each step, locating the half containing p.
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- There is only on root in the interval.
2- Must f (a) and f (b) of opposite signs.
PROCEDURE
Consider the function f (x) = x3+4x2-10= 0, [1,2]. Write a code on MATLAB using
algorithm below to find approximate a root of (f) using Bisection Method.
Answer by hand:
………… 1.3652 ………………..
Bisection Algorithm
Matlab Code:
% f(x)= x^3+4x^2-10 = 0 , root [1,2], tolerance 10^-4
s = 0;
N = 15;
a = 1;
FA = (a^3)+ 4*(a^2)- 10;
b = 2;
FB = (b^3)+ 4*(b^2)- 10;
while s <= N % condition
s = s +1;
p = a + (b - a)/2; % Bisection Method
FP = (p^3)+ 4*(p^2) - 10;
disp([s a b p FP])
if FP == 0 || (b - a)/2 < 10^(-4)
p;
end
if FA*FP > 0
a = p;
FA = FP;
else
b = p;
end
end
Matlab OutPut:
NewtonAlgorithm:
INPUT initial approximation p0; tolerance TOL; maximum number of iterations N0.
OUTPUT approximate solution p or message of failure.
Step 1 Set i=1.
Step 2 While i≤N0 do Steps 3–6.
Step 3 Set i=i+1;
Step 4 Set p=p0 −f(p0)/f'(p0).
Step 5 If|p−p0| < TOL then OUTPUT (p);
(The procedure was successful.)
STOP.
Step 6 Set p0 =p.(Update p0.)
Step 7 OUTPUT (‘The method failed after N0 iterations, N0 =’, N0); (The procedure was
unsuccessful.)
STOP.
Lab Work #6
Lagrange Interpolation
OBJECTIVES
Predictions can be obtained by using a function that fits the given data. This process is
called Interpolation.
BACKGROUND
One of the most useful and well-known classes of functions mapping the set of real
numbers into itself is the algebraic polynomials, the set of functions of the form
By this we mean that given any function, defined and continuous on a closed and bounded
interval, there exists a polynomial that is as “close” to the given function as desired. The
Lagrange polynomial takes the form
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- There is only one polynomial fit the data.
2- Polynomial with higher degree is more accurate.
PROCEDURE
Q. The upward velocity of a rocket is given as a function of time in Table 6.1. Determine the
value of the velocity at t=16 seconds by using first order Lagrange polynomial method.
Matlab Code:
D=length(X);
for i=1:D
for j=1:D
if i~=j
Z(i)=(x-X(j))/(X(i)-X(j)).*Y(i);
end
end
end
sum(Z)
Matlab Output:
ans =
393.6940
Lab Work #7
Numerical Differentiation
Three-Point and Five-Point Formulas
OBJECTIVES
Become familiar with algorithms for estimating the derivative of a mathematical function
using values of the function.
BACKGROUND
A simple two-point estimation is to compute the slope of a nearby secant line through
the points as shown in Fig. 7.1.
Three-Point Formulas:
Three Point Methods allow us to use information from both before and after the point to be
evaluated to better evaluate the derivative, see Fig.7.2. The most common three point method
is an average of a forward and backward difference derivative.
- mid point formula
Five-Point Formulas:
- mid point formula
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- Numerical differentiation is the area under the curve.
2- Three point formula is not accurate than five point formula.
PROCEDURE
x
Q. Values for f (x) = xe are given in Table 7.1. Use all the applicable three-point and five-
point formulas to approximate f,(2.0).
Table 7.1
Answer by hand:
Matlab Code:
clc
format long
a=input('enter the function in term of x (hint: use dot befor any math
operation) :','s');
f=inline(a)
p=input('Enter the point: ');
h=input('Enter the distance between the points:')
x=[(p-2*h) (p-h) p (p+h) (p+2*h)]
Fx=f(x)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%z=1*h;
i=input('choose a method to solve: \n 1.Three point End-point \n 2.three
mid-point \n 3.fivepoint mid-point \n:');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%x0=3;
if i==1
Fdx=(1/(2*h))*(-3*f(p)+4*f(p+h)-f(p+2*h));
elseif i==2
Fdx=(1/(2*h))*(f(p+h)-f(p-h));
elseif i==3
Fdx=(1/(12*h))*(f(p-2*h)-8*f(p-h)+8*f(p+h)-f(p+2*h));
end
Fdx
Matlab Output:
enter the function in term of x (hint: use dot before any math operation) :x.*exp(x)
f=
Inline function:
f(x) = x.*exp(x)
h=
0.100000000000000
x=
Columns 1 through 4
1.800000000000000 1.900000000000000 2.000000000000000 2.100000000000000
Column 5
2.200000000000000
Fx =
Columns 1 through 4
10.889365435943304 12.703199440330609 14.778112197861301 17.148956816392065
Column 5
19.855029698755072
Fdx =
22.032304866146450
Lab Work #8
Solution of Ordinary Differential Equations
Euler Method
OBJECTIVES
Become familiar with the use of Euler’s method which is the most elementary approximation
technique for solving initial-value problems.
BACKGROUND
The object of Euler’s method is to obtain approximations to the well-posed initial-
value problem
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- Initial value problem is not a differential equation.
2- Euler method is the most accurate method.
PROCEDURE
Q. Write a MATLAB program that use the Euler method with h = 0.2, N = 10, and ti = 0.2i to
obtain approximations to the solution of the initial-value problem
Euler Algorithm
Matlab Code:
clc
format short
z=input('enter the function: ','s')
f=inline(z)
y0=input('enter the initial value: ')
a=input('Enter the start-point: ')
b=input('Enter the end-point: ')
N=input('Enter the step size: ')
h=(b-a)/N
t=[a:h:b];
w(1)=y0;
disp(' i , t(i) , w(i)')
for i=1:(N+1)
w(i+1)=w(i)+h.*f(t(i),w(i));
disp([i,t(i),w(i)])%if wrote (i-1) queue start(0-10)
end
Matlab Output:
enter the function: y-t^2+1
z=
y-t^2+1
f=
Inline function:
f(t,y) = y-t^2+1
h=
0.2000
i , t(i) , w(i)
1.0000 0 0.5000
2.0000 0.2000 0.8000
3.0000 0.4000 1.1520
4.0000 0.6000 1.5504
5.0000 0.8000 1.9885
Algorithm:
Lab Work #9
Direct Solution of Linear System of Equations
Gaussian Elimination
OBJECTIVES
Become familiar with the solution linear systems of equations, which are associated with
many problems in engineering.
BACKGROUND
Direct techniques are methods that theoretically give the exact solution to the system
in a finite number of steps. In practice, of course, the solution obtained will be contaminated
by the round-off error that is involved with the arithmetic being used.
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- Gaussian elimination is an iterative method.
2- Gaussian elimination is a direct method.
PROCEDURE
Q. Write a MATLAB program using Gaussian-Elimination method to find values for x1, x2,
x3, x4 for the linear system Ax = b given by
Answer:
Matlab Code:
clc
a=[1 -1 2 -1;1 1 1 0;2 -2 3 -3;1 -1 4 3]
b=[-8; -2;-20;4]
ab = [a,b]
[R, C] = size(ab)
for j = 1:R-1
for i = j+1:R
ab(i,j:C) = ab(i,j:C)-ab(i,j)/ab(j,j)*ab(j,j:C);
end
end
x = zeros(R,1);
x(R) = ab(R,C)/ab(R,R); %%%%%x(4)=ab(4,5)/ab(4,4)...back substitution first
value.
for i = R-1:-1:1%%%%%%%%
%%%x(3)=ab(3,5)-ab(3,4)*
x(i)=(ab(i,C)-ab(i,i+1:R)*x(i+1:R))/ab(i,i);%%%%%back substitution for
last three vales.
end
x
Matlab Output:
a=
1 -1 2 -1
1 1 1 0
2 -2 3 -3
1 -1 4 3
b=
-8
-2
-20
4
ab =
1 -1 2 -1 -8
1 1 1 0 -2
2 -2 3 -3 -20
1 -1 4 3 4
R=
4
C=
5
x=
-7
3
2
2
ans =
-7
3
2
2
BACKGROUND
An iterative technique to solve the n × n linear system Ax = b starts with an initial
approximation x(0) to the solution x converges to x.
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- Seidel is an iterative method.
2- Seidel is a direct method.
PROCEDURE
The linear system Ax = b given by
E1: 10x1− x2+ 2x3= 6,
E2 : −x1+ 11x2− x3+ 3x4= 25,
E3: 2x1− x2+ 10x3− x4= −11,
E4: 3x2 − x3+ 8x4= 15
has the unique solution x = (1, 2,−1, 1)t . Write a MATLAB program using Seidel iterative
technique to find approximations x(k) to x starting with x(0) = (0, 0, 0, 0)t until
| 𝑥 𝑘 − 𝑥 𝑘−1 |∞
≤ 10−3
| 𝑥 𝑘 |∞
Algorithm
Answer:
Matlab Code:
clc
clear all
A=[ 10 -1 2 0;-1 11 -1 3;2 -1 10 -1;0 3 -1 8 ];
b=[ 6;25;-11;15 ];
x=[0 0 0 0];
NumIters=15;
D=diag(A);
A=A-diag(D);
D=1./D; %We need the inverses
n=length(x);
x=x(:); %Make sure x is a column vector
y=zeros(n,NumIters);
for j=1:NumIters
for k=1:n
x(k)=(b(k)-A(k,:)*x)*D(k);
end
y(:,j)=x;
end
y
Matlab Output:
y=
Columns 1 through 10
0.6000 1.0302 1.0066 1.0009 1.0001 1.0000 1.0000 1.0000 1.0000 1.0000
2.3273 2.0369 2.0036 2.0003 2.0000 2.0000 2.0000 2.0000 2.0000 2.0000
-0.9873 -1.0145 -1.0025 -1.0003 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000
0.8789 0.9843 0.9984 0.9998 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
Columns 11 through 15
1.0000 1.0000 1.0000 1.0000 1.0000
2.0000 2.0000 2.0000 2.0000 2.0000
-1.0000 -1.0000 -1.0000 -1.0000 -1.0000
1.0000 1.0000 1.0000 1.0000 1.0000
has the unique solution x = (1, 2,−1, 1)t . Write a MATLAB program using Jacobi’s
iterative technique to find approximations x(k) to x starting with x(0) = (0, 0, 0, 0)t until
| 𝑥 𝑘 − 𝑥 𝑘−1 |∞
𝑘
≤ 10−3
| 𝑥 |∞
Jacobi’s Algorithm:
BACKGROUND
Solving a system of nonlinear equations is a problem that is avoided when possible,
customarily by approximating the nonlinear system by a system of linear equations. When
this is unsatisfactory, the problem must be tackled directly. The most straightforward
approach is Newton’s method. Although with a loss of the extremely rapid convergence that
Newton’s method can produce.
PRE-LAB
The following pre-lab must be completed and submitted before the start of this Lab
Work. Solve the following exercises in your pre-lab report.
Tick () for True and (×) for False
1- Newton’s method can solve linear systems.
2- Newton’s method is a direct method.
PROCEDURE
The nonlinear system:
have the approximate solution (0.5, 0,−0.52359877)t. Apply Newton’s method to this
problem with x(0) = (0.1, 0.1,−0.1)t .
Algorithm
Answer:
Matlab Code:
clc;
x1=0.1; x2=0.1; x3=-0.1; n=5;
for i=1:10
f1=(3*x1)-cos(x2*x3)-(1/2);
f2=(x1^2)-(81*(x2+0.1)^2)+sin(x3)+1.06;
f3=exp(-x1*x2)+(20*x3)+((10*pi-3)/3);
x=[x1 x2 x3]';
f=[f1 f2 f3]';
J=[3 x3*sin(x2*x3) x2*sin(x2*x3); 2*x1 -162*x2-16.2 cos(x3); x2*exp(-
x1*x2) -x1*exp(-x1*x2) 20];
x=x-(J^-1)*f;
x1=x(1); x2=x(2); x3=x(3);
disp(x)
end
Matlab Output:
0.4999
0.0193
-0.5255
0.5000
0.0016
-0.5236
0.5000
0.0000
-0.5236
0.5000
0.0000
-0.5236
0.5000
-0.0000
-0.5236
0.5000
-0.0000
-0.5236
0.5000
-0.0000
-0.5236
0.5000
0.0000
-0.5236
0.5000
-0.0000
-0.5236
0.5000
0.0000
-0.5236
References
1. “Getting Started with MATLAB, Version 5”, The MathWorks, Inc., 1996.
2. D. Hanselman and B. Littlefield, “Mastering MATLAB 5. A Comprehensive Tutorial and
Reference”, Prentice Hall, Upper Saddle River, NJ, 1998.
3. K. Sigmon, “MATLAB Primer”, 5th edition, CRC Press, Boca Raton, 1998.
4. “Using MATLAB, Version 5”, The MathWorks, Inc., 1996.
5. P. Marchand, “Graphics and GUIs with MATLAB”, 2nd edition, CRC Press, Boca Raton,1999.
6. K. Sigmon, “MATLAB Primer”, 5th edition, CRC Press, Boca Raton, 1998.