Lab manual full (1) (1) (1) (1)
Lab manual full (1) (1) (1) (1)
October 2024
1|Page
Laboratory 1: Introduction
Objective
At the end of laboratory one students should be able to
know the default Layout of the MATLAB programming environment
understand rules for identifier names
understand numeric value display format commands
learn how to use MATLAB for data visualization and more
MATLAB is a programming and numeric computing platform used by millions of engineers and
scientists to analyze data, develop algorithms and create models. The name MATLAB stands for
matrix laboratory. MATLAB was originally written to provide easy access to matrix software
developed by the LINPACK and EISPACK projects but MATLAB has evolved over a period of
years.
Figure below shows the default MATLAB programming environment. It consists of four spaces:
(1) the MATLAB Command Window with the MATLAB prompt sign »
(2) the Workspace displaying the variables in the MATLAB memory, (3) the Current folder box
showing the folder’s content (Note: Current folder box enables you to interactively manage files
and folders in MATLAB), and (4) the Command history box showing a list of recent commands.
2|Page
MATLAB as a Calculator
Practice syntax of some frequently used MATLAB mathematical operations by typing the
following numerical expressions directly at the Command Window prompt.
Operation Symbol Example
Addition + 100 + 10
Subtraction - 100 -20
Multiplication * 100*99
Division / 5/98.07
Power ^ 4^7.1
Square Root sqrt() sqrt(31)
Logarithm (Natural) 1og() log(0.67)
Logarithm (Common) log10() log10(1000)
Sine sin() sin(0.8)
Cosine cos() cos(-0.6)
cosd() cosd(90)
sind() sind(90)
acosd() acosd(0)
asind() asind(1)
Y = sind(X) returns the sine of the elements in X, which are expressed in degrees.
Y=cosd(X) returns the cosine of the elements in X, which are expressed in degrees.
Commands to get help
✓ help will explain any function e.g., help sin prints the help article about the command sin
directly into the Command Window
3|Page
Variable Names
The rules for identifier names are as follows:
❖ The name must begin with a letter of alphabet after that the name can contain letters, digits
and the underscore character (e.g., num_99) but it can’t have a space. Cannot contain
punctuation characters (e.g., period, comma, semicolon).
❖ There is a limit to the length of the name the built-in function namelengthmax returns
what Maximum length is.
❖ MATLAB is case-sensitive which means that there is difference between uppercase
and lowercase letters so variables called value_1 and VALUE_1 are all different.
❖ Reserved words(keywords) can’t be used as variable name e.g., Names of built-in
functions shouldn’t be used as variable names.
Note: iskeyword returns a list of MATLAB keywords
To test if the word while is a MATLAB keyword write the following command
iskeyword('while') it returns logical 1 (true) if the character is a keyword in the
MATLAB language and logical 0 (false) otherwise.
❖ Variable names should make some sense for example if the variable is storing age of Bahir
Dar university a name such as BDU_age would make sense; x probably wouldn’t.
❖ Who shows names variables that have been defined in this command windows
❖ Whos shows more information about variables that have been defined in this
command Window
❖ Clear clears out all variables so they no longer exist
❖ Clear variable name clears out particular variable
❖ Clear varibale1 variable2 … clears out a list of variables
Note: By default, MATLAB stores all numeric variables as double-precision floating-point values.
realmax(‘double’) and realmin(‘double’) returns the largest and smallest finite floating-point
number in IEEE double precision format.
Example 1: Create a variable ftemp to store a temperature in degrees Fahrenheit (F). Convert this
to degrees Celsius (C) and store the result in a variable ctemp. The conversion factor is
C = (F – 32) * 5/9. (Hint: use input () to get ftemp value from the user and also use disp() to display
information about the program).
4|Page
Solution:
% MATLAB Program to Perform Fahrenheit to Celsius Conversion
clc % Clear MATLAB Command Window History
clear all % Clear MATLAB Workspace Memory
close all % Close all Figures and Drawings
ftemp=input('Enter Temperature to be converted:');
ctemp=(ftemp-32)*5/9;
disp('the equivalent temperature in Celsius is =')
disp(ctemp)
Note: The input function is used in assignment statement.to call it a string is passed that is the
prompt that will appear on the screen and whatever the user types will be stored in the variable
named on the left of the assignment statement.
Example 2: The voltage, V, across a resistance is given as (Ohm’s Law), V= IR where
I is the current and R the resistance. The power dissipated in resistor R is given by the expression
𝑃 = 𝐼 2 𝑅. If R = 100 Ohms and the current is increased from 0 to 20 A with increments of 2A,
write a MATLAB program that calculates the power dissipated.
Example 3: Create two variables myage and BDU_age and store 50 and 58. Use who and whos
to see the variables. Clear one of them and then use who and whos again.
Example 4: Find the value of the expression k = |𝑒 −𝑎 sin(𝑥) + 𝜋√𝑦| for a = 5, x = 2, and
y = 8.
5|Page
Matrices in MATLAB
A matrix is an array of numbers. To type a matrix into MATLAB you must
✓ begin with a square bracket, [
✓ separate elements in a row with spaces or commas (,)
✓ use a semicolon (;) to separate rows
✓ end the matrix with another square bracket.]
2 3 1 9 −2 −1
Example: Given the following matrices A =[7 4 1] and B= [5 7 3 ] find
9 −2 1 8 1 0
a. A + B
b. A – B
c. A.*B
d. A*B
✓ Single elements of a matrix are accessed as A(i,j), where i ≥ 1 and j ≥1. Zero or negative
subscripts are not supported in MATLAB.
✓ a colon (:) as the row or column specifier covers all entries in that row or column; thus
✓ A(:,j) is the jth column of A, while
✓ A(i,:) is the ith row, and
✓ A(end,:) picks out the last row of A.
Try the following commands and explain their function.
A(3,3)
A(2,:)
A(end,:)
A(end,1)
A’
det(A)
E=zeros(4,4)
F=ones(4,4)
6|Page
G=rand(4,4)
V=diag(G)
Y=G(2:3,:)
W= G(:,2:3)
G(:,1:2)=[]
Display formats
by default MATLAB displays numbers to 4 decimal places. You can always see more digits in any
answer by typing:
⨠ format long
By contrast, typing:
⨠ format short
returns MATLAB to displaying the default form, rounded to four decimal places.
Practice the following numeric value display format commands
Command Description Example
format short fixed-decimal format with 4 digits after the 351/7
decimal point.
format long fixed-decimal format with 15 digits after the Format long
decimal point for double values, and 7 digits after 351/7
the decimal point for single values.
format short e Short scientific notation with 4 digits after the format short e
decimal point. 351/7
format long e Long scientific notation with 15 digits after the format long e
decimal point for double values, and 7 digits after 351/7
the decimal point for single values.
format short G Short, fixed-decimal format or scientific notation, format short G
whichever is more compact, with a total of 5 351/7
digits.
format long G Long, fixed-decimal format or scientific notation, format long G
whichever is more compact, with a total of 15 351/7
digits for double values, and 7 digits for single
values.
format bank Currency format with 2 digits after the decimal format bank
point. 351/7
format rat Ratio of small integers. format rat
pi
7|Page
format compact Eliminates empty lines to allow more lines with format compact
information displayed on the screen 351/7
format loose Adds empty lines (opposite of compact) format loose
351/7
Plotting
The plot command needs at least one argument If there is no open figure, MATLAB will open a
new one and will plot the argument (an array) versus its index. If there are two arrays as input
arguments, MATLAB will take the first array to be the x-coordinates, and the second array, the y
coordinates.
Example 1: lets plot x.^2-20 using MATLAB
clc % Clear MATLAB Command Window History
clear all % Clear MATLAB Workspace Memory
close all % Close all Figures and Drawings
x=-5:10; %values of the argument
y= x.^2 -20; % the function
plot(x,y,'r*-')
title('plotting x.^2-20 using MATLAB')
xlabel('x axis')
ylabel('y axis')
grid on
Note: third string argument can specify the type of line, color and marker of the plotted line
symbols that can be used are listed in the table below. You can also change Line Width and
Marker Size, Marker Edge Color and Marker Face Color. Try the following.
Example 2
clc % Clear MATLAB Command Window History
clear all % Clear MATLAB Workspace Memory
close all % Close all Figures and Drawings
x=-5:10; %values of the argument
8|Page
y= x.^2 -20; % the function
plot(x,y,'rd-','LineWidth',4,'MarkerSize',15,'MarkerEdgeColor','k','MarkerFaceColor','g')
title('plotting x.^2-20 using MATLAB')
xlabel('x axis')
ylabel('y axis')
grid on
Table 1 type of line, color and marker of the plotted line symbols that can be used with plot
function
Example 3: plot the function y = 3x3-26x+10, and its first derivative y'=9x2-26 and second
derivative y"= 18x, for 0≤x≤5, all in the same plot. Using the hold on, hold off command
clc
clear
close all
x = 0:1:5;
y = 3*x.^3-26*x+10;
dy = 9*x.^2-26;
ddy = 18*x;
% plot(x,y,x,dy,x,ddy);
plot(x,y,'-bs');
hold on
9|Page
plot(x,dy,'--rd');
plot(x,ddy,':k*');
hold off
title('Plotting multiple graphs')
xlabel('x axis')
ylabel('y axis')
legend('y','first derivative','second derivative');
Example 4: plot the function y = 3x3-26x+10, and its first derivative y'=9x2-26 and second
derivative y"= 18x, for 0≤x≤5, Using the Subplot command.
clc
clear
close all
x = 0:1:5;
y = 3*x.^3-26*x+10;
dy = 9*x.^2-26;
ddy = 18*x;
subplot(2,2,1)
% subplot(m,n,p) creates an axes in the p-th pane of a figure divided into an m-by-n matrix of
%rectangular panes.
plot(x,y,'-bs');
title('plot of the function')
xlabel('x axis')
ylabel('y axis')
grid on
subplot(2,2,2)
plot(x,dy,'--rd');
title('plot of first derivative')
xlabel('x axis')
10 | P a g e
ylabel('y axis')
grid on
subplot(2,2,3)
plot(x,ddy,':k*');
title('Plot of second derivative')
xlabel('x axis')
ylabel('y axis')
grid on
Exercise:
1. The voltage v and current I of a certain diode are related by the expression
𝑉𝑑
𝐼𝐷 = 𝐼𝑠 𝜖 𝜂𝑉𝑡
If 𝐼𝑠 = 1.0*10−14 𝐴 𝜂= 2.0 and VT = 26 mV, plot the current versus voltage curve of the
diode for diode voltage between 0 and 0.6 volts using MATLAB.
2. A chemical plant releases an amount A of pollutant into a stream. The maximum
concentration C of the pollutant at a point which is a distance X from the plant is:
𝐴 2
C = 𝑋 √𝜋𝑒 Create variables for the values of A and X and then for C. Assume that the distance
X is in meters. Experiment with different values for X.
3. Consider the following electric circuit
11 | P a g e
With the given values of resistance, inductance, and capacitance, the impedance 𝑍𝑎𝑏 as a
function of the radian frequency ω can be computed from the following expression.
106
104 − 𝑗( 𝜔 )
𝑍𝑎𝑏 = 𝑍 = 10 +
105
10 + 𝑗(0.1𝜔 − 𝜔 )
12 | P a g e
Example 2: Calculate the summations ∑𝑁 𝑝
𝑗=1 𝑗 for p equal to one, two and three for N = 6.
clc
N=6;
for p = 1:3
sums(p) = 0.0;
for j = 1:N
sums(p) = sums(p)+j^p;
end
end
disp(sums)
Example 3: Write a MATLAB script that will accept an array of numeric values from the user
and then return a statement ‘monotonically increasing’ if the elements of the input array increase
monotonically (i.e., each element is larger than the previous). Otherwise return a statement stating
that it is ‘not monotonically increasing’.
13 | P a g e
Solution:
clc
clear
A = input('Enter a numerical vector array in the form [5 8 9 8 7] \n');
for i=2:length(A)
if A(i) > A(i-1)
flag = 0;
else
flag = 1;
disp('Not monotonically increasing');
break;
end
end
if flag ==0
disp('Monotonically increasing');
end
14 | P a g e
end
switch statement
The following is the syntax of a switch statement:
switch(expression)
case expression:
statements
case expression:
<statements>
…
…
…
otherwise
statements
end
Example 5:
choice = input('Enter first word of the stream you intend to join\n ', 's');
switch choice
case {'Industrial', 'industrial'}
fprintf('requires a total of 323 credit hours.\n')
case {'Communication', 'communication'}
fprintf('requires a total of 319 credit hours.\n')
case {'Electronics', 'electronics'}
fprintf('requires a total of 324 credit hours.\n')
case {'Power', 'power'}
fprintf('requires a total of 318 credit hours.\n')
case {'Computer', 'computer'}
fprintf('requires a total of 316 credit hours.\n')
otherwise
fprintf('unavailable data!')
end
15 | P a g e
Functions
We shall start with a very simple example:
function [output] = xsq(input)
output = input.ˆ2;
end
which we will save as xsq.m. It is important that we get the syntax for functions correct so we’ll
go through this example in some detail.
The first line of xsq.m tells us this is a function called xsq which takes an input called input and
returns a value called output. The input is contained in round brackets, whereas the output is
contained within square brackets. It is crucial for good practice that the name of the function xsq
corresponds to the name of the file xsq.m (without the .m extension), although there is some
flexibility here. The second line of this function actually performs the calculation, in this case
squaring the value of the input, and storing this result in the variable output. Having written our
function, we can now access it from within MATLAB. Consider the following:
x = 1:10;
y = xsq(x)
Here we have initialized the vector x to contain the first ten integers. We call the function in the
second line and assign the result, in this case x.ˆ2, to the variable y. Notice that we have called the
function with the argument x and not something called input. The variables input and output are
local variables that are used by the function; they are not accessible to the general MATLAB
workspace. When the function is run it merely looks at what is given as the argument.
Example 6: Suppose we now want to construct the squares and cubes of the elements of a vector.
We can use the code
function [sq,cub] = xpowers(input)
sq = input.^2;
cub = input.^3;
end
Again, the first line defines the function xpowers, which has two outputs sq and cub and one input.
The second and third lines calculates the values of input squared and cubed. This function file must
be saved as xpowers.m and it can be called as follows:
x = 1:10;
[xsq,xcub] = xpowers(x)
16 | P a g e
Variable number of input arguments
The function we saw in example six has fixed number of input and output arguments which is two
and one respectively.
If we call that function using three input argument MATLAB will throw error.
However, it is also possible to have variable number of input and output argument.
A built-in cell array varargin can be used to store a variable number of input arguments. These are
cell arrays because the arguments could be different types.
the function nargin returns the number of input arguments that were passed to the function during
function call.
Example 7
The sum of a geometric series is given by
1 + 𝑟 + 𝑟2 + 𝑟3 + . . . + 𝑟𝑛
Write a function called geomser that will receive a value for r and calculate and return the sum of
the geometric series. If a second argument is passed to the function, it is the value of n; otherwise,
the function generates a random integer for n (ranging from 1 to 100).
17 | P a g e
Variable number of output arguments
A built-in cell array Varargout can be used to store a variable number of output arguments. These
are cell arrays because the arguments could be different types.
The function nargout determines how money output arguments are expected to be returned from a
function.
Example 8
For a project we need some material to form a rectangle. Write a function called calcarean that
will receive the length and width of a rectangle in meter as input arguments and will return the
area of a rectangle in square meter and possibly also in square inches depending on the number of
output arguments.
Note:1 Square Meter is equal to 1550.0031 square inches
18 | P a g e
classwork
1. Develop an M-file function that is passed a numeric grade from 0 to 100 and returns a letter
grade according to the following Bahir Dar university grading system. The first line of the
function should be function grade = lettergrade(score)
4. Write a function called maxi to return the index of the most positive element in a vector.
In other words, imax = maxi(v) returns imax such that v(imax) ≥v(i) for all i.
5. The Goldbach conjecture asserts that every even integer greater than 2 can be expressed as
the sum of two primes. Write a script that will accept an even integer and then it will return
primes p1 and p2 that satisfy the condition n = p1 + p2. Note that the primes are not always
unique. The program should just return one such combination of the primes
19 | P a g e
Laboratory 3
tic
data=[0.3 0.4 0.5;1 2 3];
total=0;
for rowIdx = 1:size(data,1)
for colIdx = 1:size(data,2)
total = total + data(rowIdx,colIdx)
end
end
toc
20 | P a g e
Move Loop-Invariant Code Out of the Loop
this is perhaps the most used optimization technique. any expression or computation that is
unnecessarily repeated in a loop should only be done once. The idea is to move this common
expression outside the loop, so that it is only evaluated once.
In the following example, we have two invariants: sin(x) is common to both loops, whereas the
expression sin(x)/outerIter is common only to the inner loop:
Write the following codes then use Matlab profiler as follows then compare the result and
justify your answer
21 | P a g e
Unroll Simple Loops
The idea is to replace a loop with repeated sets of the loop contents. This is sometimes done
automatically by the JIT optimizer, but can also be done manually by the programmer. For
example, the simple loop
tic
a=[0 0 0 0 0]
for idx = 1 : 5
a(idx) = sin(1/idx)
end
toc
the above code can be replaced with the following code:(compare elapsed time)
tic
a(1) = sin(1/1);
a(2) = sin(1/2);
a(3) = sin(1/3);
a(4) = sin(1/4);
a(5) = sin(1/5);
toc
Note: The potential benefit is the removal of the run-time loop checks and branches. Naturally,
this technique is only feasible for very short loops and very simple contents.
A variant of loop unrolling, called loop peeling takes one or more iterations that are special in
some way out of the loop. This simplifies the loop’s contents and prevents branching with its
associated JIT and pipelining penalties. For example, let’s compute Fibonacci’s sequence in a
naïve manner:
tic
for idx = 1 : 100
if idx < 3
fibonacci(idx) = 1
else
fibonacci(idx) = fibonacci(idx-1) + fibonacci(idx-2);
end
end
toc
22 | P a g e
and now with loop peeling of the initial two loop iterations:
tic
fibonacci = [0, 1];
for idx = 3 : 100
fibonacci(idx) = fibonacci(idx-1) + fibonacci(idx-2);
end
toc
tic
data = rand(5000,5000);
% Row-first loop (natural order, bad for
performance)
total = 0;
for rowIdx = 1:size(data,1)
for colIdx = 1:size(data,2)
total = total + data(rowIdx,colIdx);
end
end
toc
tic
data = rand(5000,5000);
total = 0;
for colIdx = 1:size(data,2)
for rowIdx = 1:size(data,1)
total = total + data(rowIdx,colIdx);
end
end
toc
23 | P a g e
Note: Switching loop order does not always improve performance. sometimes the reverse is true.
Remember that other factors besides the memory allocation order affect performance. For
example, switching loop order may mean that a conditional expression is now evaluated in the
inner loop rather than the outer loop, which could have a devastating impact on performance that
would far outweigh any benefit gained from the improved memory access.
Minimize Dereferencing
Accessing object properties/methods, array elements, and structure fields incurs a runtime
processing overhead (including boundary and security checks). Depending on the frequency of the
usage, the loop size and the average iteration run-time, this overhead can be a significant portion
of the loop’s total run-time. The simple act of caching such indirect data accesses in a simple
variable negates this performance penalty and can often bring about important speedups:
Example: try the following codes and compare the elapsed time
tic
% Simple loop accessing an array element
a = [0,0];
for idx = 1 : 1e8
a(2) = a(2) + idx;
end
toc
tic
% The same loop using a temporary simple accumulator - faster
a = [0,0];
b = 0;
for idx = 1 : 1e8
b = b + idx; % b instead of a(2)
end
a(2) = b;
toc
24 | P a g e
Use the Loop Index Rather than Counters
not using the loop index makes the code more complex and harder to maintain. Importantly,
performance may also suffer: try the following codes and compare the elapsed time
tic
data = rand(1,1e6);
% Original code: uses counter rather than the loop index
k = 0; total = 0;
for idx = 1 : numel(data)
k = k + 1;
total = total + data(k);
end
toc
tic
% Optimized loop: uses only the loop index, faster and simpler
total = 0;
for idx = 1 : numel(data)
total = total + data(idx);
end
toc
25 | P a g e
Parallelization using MathWorks toolboxes
MathWorks offer MATLAB toolbox called Parallel Computing Toolbox (PCT) dedicated
to parallelization.
PCT is a collection of high-level, easy-to-use MATLAB functions and language constructs that
enable solving computationally intensive and data-intensive problems using multicore CPU
processors and GPUs.
Using parfor-Loops
The syntax and semantics of a parfor-loop in MATLAB software are the same as of the standard
for-loop: MATLAB executes a series of statements of the loop body over a range of values. The
necessary data on which parfor operates are sent from the client to a group of workers (computing
processes), where the actual computation happens, and the results are sent back to the client and
assembled together. The workers should be identified and reserved with the parpool command.
Each execution of the body of a parfor-loop is an iteration. MATLAB workers evaluate iterations
in unspecified order, and independently of each other. Since each iteration is independent, there is
no guarantee that the iterations are interleaved in any way, nor is there any need for this. If the
number of workers is equal to the number of loop iterations, each worker performs a single loop
iteration. If there are more iterations than workers, some workers perform several loop iterations.
This is handled in an entirely automated manner, and we have no control over the allocation.
Using spmd
Along with parfor-loops, PCT also provides the spmd (single program, multiple data) language
construct, which allows seamless interleaving of serial and parallel programming.
The spmd statement defines a block of code to be run simultaneously on multiple workers that
should be reserved using parpool. The “multiple data” aspect of spmd means that although the
spmd statement runs identical code on all workers, each worker can have different, unique data for
that code. Therefore, multiple data sets can be accommodated by multiple workers.
26 | P a g e
Laboratory 4: Bracketing Methods
27 | P a g e
break;
end
iteration=n
ea=abs((c-z)/c)*100
z=c
end
if(k*v<0)
fprintf('THE ROOT IS FOUND TO BE=%f\n',z)
fprintf('THE ROOT IS FOUND AFTER N=%d ITERATIONS\n',n)
end
Example 2: Determine the root of 𝑥 3 + 4𝑥 2 - 10 using false position method. Employ initial
guesses of xl = 1 and xu = 2 and iterate until the estimated error ℇa falls below a level of ℇs =
0.000001%.
Solution:
% MATLAB Algorithm to find root of x^3+4x^2 -10 using false
position method
% Error specified is 0.000001
% Ea is approximate error
% input() is MATLAB built in function that takes(requests) user
input
fprintf('FALSE POSITION MATLAB ALGORITHM:\n')
x1=input('ENTER LOWER BOUND FOR FALSE POSITION METHOD:=');
xu=input('ENTER UPPER BOUND FOR FALSE POSITION METHOD:=');
ea=100;
z=0;
n=0;
while ea>0.000001
fxu=xu^3+4*xu^2 -10;
fx1=x1^3+4*x1^2 -10;
if(fx1*fxu<0)
n=n+1;
xr=xu-(fxu*(x1-xu))/(fx1-fxu);
fxr=xr^3+4*xr^2 -10;
if(fx1*fxr<0)
xu=xr;
else(fxr*fxu<0)
28 | P a g e
x1=xr;
end
else
fprintf('NO root in the given range! \n ')
break;
end
iteration=n
ea=abs((xr-z)/xr)*100
z=xr
end
if(fx1*fxu<0)
fprintf('THE ROOT IS FOUND TO BE=%f\n',z)
fprintf('THE ROOT IS FOUND AFTER N=%d ITERATIONS\n',n)
end
Exercise 1: Determine the root of 2𝑥 3 - 2x - 5 using bisection method. Employ initial guesses of
xl = 1 and xu = 2 and iterate until number of iterations is less than or equal to four.
Exercise 2: Determine the root of 2𝑥 3 - 2x - 5 using false position method. Employ initial guesses
of xl = 1 and xu = 2 and iterate until number of iterations is less than or equal to four.
Exercise 3: Determine the root of f(x) =𝑥 3 + 4𝑥 2 - 10 and the polynomial given above using
MATLAB’s built-in function called roots (). You can use help to understand the syntax
29 | P a g e
LABORATORY 5: OPEN METHODS
30 | P a g e
Example 2: Use Newton-Raphson method to locate the root of f(x) = 2x 3 -𝑥 2 -2. Start with an
initial guess of x = 1.5 and iterate until the estimated error ℇa falls below a level of ℇs = 0.000009%.
Solution:
% Newton-Raphson simple MATLAB algorithm to find root of f(x)=2x^3-x^2 -2
% Variables f and df are a function handle. The @ operator creates the handle
% The parentheses () immediately after the @ operator include the function
% Input argument that is x
% Initial guess is 1.5
f=@(x)2*x^3 - x^2 -2
df=@(x) 6*x^2 - 2*x
x=1.5;
ea=100;
n=0;
while ea>0.000009
n=n+1
x1=x-(f(x)/df(x));
ea=abs((x1-x)/x1)*100
x=x1;
root=x1
end
31 | P a g e
Class Activity 1. Use simple fixed-point iteration to locate the root of f(x) = 𝐞−𝐱 - x.
Start with an initial guess of x = 0 and iterate until the estimated error ℇa falls below a level
of ℇs = 0.00399%.
2. Modify the MATLAB code of simple fixed-point iteration to output value of Number of
iterations, root and approximate error without using fprintf function.
3. Use Newton-Raphson method to locate the root of f(x) = 𝐞−𝐱 - x. Start with an initial
guess of x =0 and iterate until the estimated error ℇa falls below a level of ℇs = 0.00399%.
Exercise: Check your result in Example 1 and 2 by solving the problem manually iterate
until number of iterations is less than or equal to four
32 | P a g e
Laboratory 6: Implementation of secant and Modified secant
method using MATLAB
Example 1: Determine the root of 𝑥 3 - x - 1 using secant method. Employ initial estimates of
x1=1 and xu=2 and iterate until the estimated error ℇa falls below a level of ℇs = 0.000001%.
Solution:
% MATLAB Algorithm to find root of x^3 - x -1 using secant method
% Error specified is 0.000001
fprintf('SECANT MATLAB ALGORITHM:\n')
x1=input('enter first initial estimate :=');
xu=input('enter second initial estimate:=');
ea=100;
z=0;
n=0;
while ea>0.000001
n=n+1;
fxu=xu^3 - xu -1;
fx1=x1^3 - x1 -1;
xr=xu-(fxu*(x1-xu))/(fx1-fxu);
iteration=n
ea=abs((xr-z)/xr)*100
z=xr
x1=xu;
xu=xr;
end
33 | P a g e
fprintf('THE ROOT IS FOUND TO BE=\n')
z
fprintf('THE ROOT IS FOUND AFTER N=%d ITERATIONS\n',n)
Class Activity: Determine the root of 𝒆−𝒙 - x using secant method. Employ initial estimates of
x1=0 and xu=1 and iterate until the estimated error ℇa falls below a level of ℇs = 0.000001%.
Recall that the true root is 0.56714329
34 | P a g e
end
fprintf('THE ROOT IS =%f\n')
x
fprintf('THE ROOT IS FOUND AFTER N=%d ITERATIONS\n',n)
Class Activity:
modify the initial values with the following points and see which root you are going to get.
x=0.1, -0.3, -0. 7 Note: The Actual roots of the above equation are 0, -1, 2.4142 and -0.4142
Exercise: Check your result in Example 1 and 2 by solving the problem manually iterate until
number of iterations is less than or equal to four.
35 | P a g e
Laboratory 7: Implementation of Müller’s method using
MATLAB
Example: Use Müller’s method with initial guesses of x0=0, x1=1, and x2=2 to determine a root
of the equation f(x)= 2𝑥 3 -4x -10. iterate until the estimated error ℇa falls below a level of ℇs =
0.00000000012.
Solution:
fprintf('MATLAB implementation of muller method\n')
x0=0;
x1=1;
x2=2;
n=0;
ea=100;
while ea>0.00000000012
fx0=2*x0^3-4*x0-10;
fx1=2*x1^3-4*x1-10;
fx2=2*x2^3-4*x2-10;
h0=x1-x0;
h1=x2-x1;
d0=(fx1-fx0)/h0;
d1=(fx2-fx1)/h1;
a=(d1-d0)/(h0+h1);
b=a*h1+d1;
c=fx2;
rad=sqrt(b*b - 4*a*c);
if(abs(b + rad)> abs(b - rad ))
den= b + rad;
else
36 | P a g e
den=b – rad;
end
dxr=(-2*c)/den;
x3= x2 + dxr
ea=abs((x3-x2)/x3)*100
x0=x1;
x1=x2;
x2=x3;
n=n+1
end
fprintf('THE ROOT IS FOUND AFTER N=%d ITERATIONS\n',n)
if(imag(x3) ~ = 0)
fprintf('THE ROOT IS FOUND TO BE=%f + %fi\n',real(x3),imag(x3))
else
fprintf('THE ROOT IS FOUND TO BE=%f\n',x3)
end
Class Activity: Use Müller’s method with initial guesses of x0=4.5 x1=5.5 and x2=5 to determine
a root of the equation f(x)= 𝒙𝟑 -13x-12
Exercise: Check your result in Example 1 by solving the problem manually iterate until number
of iterations is less than or equal to four.
37 | P a g e
LABORATORY 8: MATLAB IMPLEMENTATION OF CRAMER’S RULE,
NAIVE GAUSS ELIMINATION AND GAUSS-SEIDEL METHOD
Class Activity 1: Check your result in Example 1 by solving the problem manually
2. Use Cramer’s rule to solve
x1 + x2 +2x3=22
3x1 + 6x2 +9x3=12
6x1 + 6x2 + 8x3=10
38 | P a g e
Example 2: Use Naive Gauss elimination to solve
x + y + z=3
2x - y - z =3
x - y + z =9
Solution:
clc;
clear all;
given=[1 1 1;2 -1 -1;1 -1 1];
b=[3;3;9];
% Augmented matrix
A=[given b];
% Code for the elimination step of Gauss elimination method
% Size(A,1) returns the size of the first dimension of A
for i=1:size(A,1)
for j=i+1:size(A,1)
multiplier=A(j,i)./A(i,i);
A(j,:)=A(j,:)-multiplier.*A(i,:);
end
end
% size(given,2) returns the size of the second dimension of given
x=zeros(1,size(given,2));
% Code for the back substitution step of Gauss elimination method
for i=size(A,1):-1:1
hg=sum(A(i,i+1:end-1).*x(i+1:end));
x(i)=(A(i,end)-hg)./A(i,i);
end
x
Class Activity: Solve the following System of Linear Equations using MATLAB
Problem Statement. Use Gauss elimination to solve
3x1 - 0.1x2 - 0.2x3 = 7.85
0.1x1 + 7x2 - 0.3x3 = -19.3
0.3x1 - 0.2x2 + 10x3 = 71.4
39 | P a g e
Example 3: Develop an M-file to implement Gauss-Seidel method
obtain the solution for
3x1 − 0.1x2 − 0.2x3 = 7.85
0.1x1 + 7x2 − 0.3x3 = −19.3
0.3x1 − 0.2x2 + 10x3 = 71.4
Note that the solution is x1 = 3, x2 = −2.5, and x3 = 7.
function x = GaussSeidel(A,b,es,maxit)
% GaussSeidel: Gauss Seidel method
% x = GaussSeidel(A,b): Gauss Seidel without
%relaxation
% input:
% A = coefficient matrix
% b = right hand side vector
% es = stop criterion (default = 0.00001%)
% maxit = max iterations (default = 50)
% output:
% x = solution vector
if nargin<2
error('at least 2 input arguments required')
end
if nargin<4|isempty(maxit),maxit=50;end
if nargin<3|isempty(es),es=0.00001;end
[m,n] = size(A);
if m~=n
error('Matrix A must be square');
end
C = A;
for i = 1:n
C(i,i) = 0;
x(i) = 0;
end
x = x';
40 | P a g e
for i = 1:n
C(i,1:n) = C(i,1:n)/A(i,i);
end
for i = 1:n
d(i) = b(i)/A(i,i);
end
iter = 0;
while (1)
xold = x;
for i = 1:n
x(i) = d(i)-C(i,:)*x;
if x(i) ~= 0
ea(i) = abs((x(i) - xold(i))/x(i)) * 100;
end
end
iter = iter+1;
if max(ea)<=es | iter >= maxit, break, end
end
Exercise
An electrical circuit containing resistors and voltage sources is depicted in the figure below. Create
a MATLAB program that uses Kirchhoff’s law to calculate the current flowing through each
resistor.
R6 = 10 Ω, R7 = 10 Ω, R8 = 15 Ω
41 | P a g e
Laboratory 9 regression
Along with the slope and intercept, compute the standard error of the estimate and the correlation
coefficient. Plot the data and the regression line.
clc
clear
% x = independent variable
% y = dependent variable
x=[0 2 4 6 9 11 12 15 17 19]
y=[5 6 7 6 9 8 7 10 12 12]
n = length(x);
if length(y)~=n
error('x and y must be same length');
end
sumx=0;
sumxy=0;
st=0;
sr=0;
sumy=0;
sumx2=0;
for i=1:n
sumx=sumx+x(i);
sumy=sumy+y(i);
sumxy=sumxy+x(i).*y(i);
sumx2=sumx2+x(i).*x(i);
end
xm=sumx/n;
ym=sumy/n;
42 | P a g e
a1=(n*sumxy-sumx.*sumy)/(n*sumx2-sumx.*sumx)
a0= ym-a1*xm
for i=1:n
st=st+(y(i)-ym)^2
sr=sr+(y(i)-a1*x(i)-a0)^2
end
%The standard deviation
sy=sqrt(st/(n-1))
%standard error of the estimate
syx=sqrt(sr/(n-2))
%coefficient of determination
r2=(st-sr)/st
%correlation coefficient
r=sqrt(r2)
% then create plot of the given data points and best fit line
yp = a0 + a1*x;
plot(x,y,'o')
hold on
plot(x,yp,'r*-')
hold off
grid on
43 | P a g e
Example 2: use the following code fragment in combination with gauss elimination method to
fit second-order polynomial to the data given below.
Calculate standard error of the estimate, coefficient of determination and correlation coefficient.
x 0.75 2 3 4 6 8 8.5
clc
clear
x=[0.75 2 3 4 6 8 8.5];
y=[1.2 1.95 2 2.4 2.4 2.7 2.6];
order=2;
n=length(x)
for i=1:order+1
for j=1:i
k=i+j-2;
sum=0;
for m=1:n
sum=sum+(x(m))^k;
end
a(i,j)=sum
a(j,i)=sum
end
sum=0
for m=1:n
sum=sum+y(m)*(x(m))^(i-1)
end
a(i,order+2)=sum
end
44 | P a g e
Example 3: The following data were created from the equation y = 5 + 4x1 − 3x2:
x1 x2 y
0 0 5
2 1 10
2.5 2 9
1 3 0
4 6 3
7 2 27
Open Microsoft excel enter the above data and save it as dataset1.csv
First import dataset1.csv into workspace using the following command. Please don’t forget to
include the file path inside quotation mark below
trainingdataset=readtable('please enter dataset path')
Then perform regression analysis in the regression learner app by using the following steps.
In the apps tab in the Machine Learning group, click on Regression Learner.
In the New Session tab click from workspace
Choose independent variables, dependent variables, and validation scheme
Then click start session
Choose the linear regression model, hit train, and wait for the training to be completed.
Export the trained model to a workspace variable named trainedModel
To perform prediction using the trained model we exported, first create excel file that contains
values of x1 and x2 only and save it as testdataset.csv
import testdataset.csv into workspace using the following command
testdataset=readtable('please enter test dataset path here')
then perform prediction using the following command
yfit = trainedModel.predictFcn(testdataset)
45 | P a g e
Laboratory 10 Interpolation
Example 1: fit third-order polynomial to the following points using Newton’s interpolating
polynomial estimate ln 2
x 1 4 5 6
y 0 1.386294 1.609438 1.791559
x=[1 4 5 6];
y=[0 1.386294 1.609438 1.791559];
xx=2;
n=length(x);
if length(y)~=n
error('x and y must be same length')
end
for i=1:n
fdd(i,1)=y(i)
end
for j=2:n
for i=1:n-j+1
fdd(i,j)=(fdd(i+1,j-1)-fdd(i,j-1))/(x(i+j-
1)-x(i))
end
end
xterm=1;
yint=fdd(1,1)
for j=1:n-1
xterm=xterm*(xx-x(j));
yint=yint+fdd(1,j+1)*xterm
end
46 | P a g e
Example 2: Use a Lagrange interpolating polynomial to evaluate ln 2 on the basis of the data
given below.
x 1 4 5 6
y 0 1.386294 1.609438 1.791559
47 | P a g e
Exercise
✓ Manually construct the divided-difference table. Use the MATLAB script in example 1 to
check your calculations.
✓ Manually compute ln 2 using data given in example 2. Use the Lagrange function
to check your calculations.
✓ Ohm’s law states that the voltage drop V across an ideal resistor is linearly proportional
to the current i flowing through the resister as in V = i R, where R is the resistance.
However, real resistors may not always obey Ohm’s law. Suppose that you performed
some very precise experiments to measure the voltage drop and corresponding current for
a resistor. The following results suggest a curvilinear relationship rather than the straight
line represented by Ohm’s law
To quantify this relationship, a curve must be fit to the data. Because of measurement error,
regression would typically be the preferred method of curve fitting for analyzing such experimental
data. However, the smoothness of the relationship, as well as the precision of the experimental
methods, suggests that interpolation might be appropriate. Use a fifth-order interpolating
polynomial to fit the data and compute V for i = 0.10.
48 | P a g e
Laboratory 11 Numerical Integration
Example 1:
Use the two-segment trapezoidal rule to estimate the integral of
f(x) = 0.2 + 25x − 200x 2 + 675x3 − 900x4 + 400x5
from a = 0 to b = 0.8. experiment with number of segments and explain your observation. Recall
that the correct value for the integral is 1.640533.
function I = trap(func,a,b,n,varargin)
% trap: composite trapezoidal rule quadrature
% I = trap(func,a,b,n,pl,p2,...):
% composite trapezoidal rule
% input:
% func = name of function to be integrated
% a, b = integration limits
% n = number of segments (default = 100)
% pl,p2,... = additional parameters used by func
% output:
% I = integral estimate
if nargin<3
error('at least 3 input arguments required')
end
if ~(b>a)
error('upper bound must be greater than lower')
end
if nargin<4|| isempty(n)
n=100
end
x = a;
h = (b - a)/n;
s=func(a,varargin{:});
for i = 1 : n-1
x = x + h;
s = s + 2*func(x,varargin{:});
end
s = s + func(b,varargin{:});
I = (b - a) * s/(2*n);
49 | P a g e
Example 2: estimate the integral of
f(x) = 0.2 + 25x − 200x 2 + 675x3 − 900x4 + 400x5
from a = 0 to b = 0.8. using the following unequally spaced values of x. Recall that the correct
value for the integral is 1.640533.
x 0 0.12 0.22 0.32 0.36 0.4 0.44 0.54 0.64 0.7 0.8
f(x) 0.2 1.309729 1.305241 1.74 2.074 2.4 2.842985 3.507297 3.181 2.363 0.232
3393 903 56 929
function I = trapuneq(x,y)
% trapuneq: unequal spaced trapezoidal rule quadrature
% I = trapuneq(x,y):
% Applies the trapezoidal rule to determine the integral
% for n data points (x, y) where x and y must be of the
% same length and x must be monotonically ascending
% input:
% x = vector of independent variables
% y = vector of dependent variables
% output:
% I = integral estimate
if nargin<2
error('at least 2 input arguments required')
end
if any(diff(x)<0)
error('x not monotonically ascending')
end
n = length(x);
if length(y)~=n
error('x and y must be same length')
end
s = 0;
for k = 1:n-1
s = s + (x(k+1)-x(k))*(y(k)+y(k+1))/2;
end
I = s;
50 | P a g e
Example 3: Use multiple-application version of Simpson’s 1/3 rule with n=4 to estimate the
integral of
f(x) = 0.2 + 25x − 200x 2 + 675x3 − 900x4 + 400x5
from a = 0 to b = 0.8.
function I=Sim13m(n,a,b,f)
h=(b-a)/n;
x=a;
sum=f(x);
for i=1:2:n-2
x=x+h;
sum=sum+4*f(x);
x=x+h;
sum=sum+2*f(x);
end
x=x+h;
sum=sum+4*f(x)
sum=sum+f(b)
I=(b-a)*sum/(3*n)
end
function[q,ea,iter]=romberg(func,a,b,es,maxit,varargin)
% romberg: Romberg integration quadrature
% q = romberg(func,a,b,es,maxit,p1,p2,...):
% Romberg integration.
% input:
% func = name of function to be integrated
% a, b = integration limits
% es = desired relative error (default = 0.000001%)
% maxit = maximum allowable iterations (default = 30)
% pl,p2,... = additional parameters used by func
% output:
% q = integral estimate
% ea = approximate relative error (%)
51 | P a g e
% iter = number of iterations
if nargin<3
error('at least 3 input arguments required')
end
if nargin<4||isempty(es)
es=0.000001;
end
if nargin<5||isempty(maxit)
maxit=50;
end
n = 1;
I(1,1) = trap(func,a,b,n,varargin{:});
iter = 0;
while iter<maxit
iter = iter+1;
n = 2^iter;
I(iter+1,1) = trap(func,a,b,n,varargin{:});
for k = 2:iter+1
j = 2+iter-k;
I(j,k) = (4^(k-1)*I(j+1,k-1)-I(j,k-1))/(4^(k-1)-1);
end
ea = abs((I(1,iter+1)-I(2,iter))/I(1,iter+1))*100;
if ea<=es
break;
end
end
q = I(1,iter+1);
52 | P a g e
Laboratory 12 Solving Ordinary Differential Equations using
MATLAB
Example 1: Use Euler’s method to integrate y’ = 4e0.8t − 0.5y from t = 0 to 4 with a step size of
1. The initial condition at t = 0 is y = 2. Note that the exact solution can be determined
analytically as
4
y’ = 1.3(e0.8t – e-0.5t) + 2e-0.5t
53 | P a g e
Example 2: Use the classical fourth-order RK method to integrate the.
f(x, y) = 4e0.8x − 0.5y using h = 0.5 with y(0) = 2 from x = 0 to 0.5.
function [tp,yp] = rk4sys(dydt,tspan,y0,h,varargin)
% rk4sys: fourth-order Runge-Kutta for a system of ODEs
% [t,y] = rk4sys(dydt,tspan,y0,h,p1,p2,...): integrates
% a system of ODEs with fourth-order RK method
% input:
% dydt = name of the M-file that evaluates the ODEs
% tspan = [ti, tf]; initial and final times with output
% generated at interval of h, or
% =[t0 t1 ... tf]; specific times where solution output
% y0 = initial values of dependent variables
% h = step size
% p1,p2,... = additional parameters used by dydt
% output:
% tp = vector of independent variable
% yp = vector of solution for dependent variables
if nargin<4,error('at least 4 input arguments required'), end
if any(diff(tspan)<=0),error('tspan not ascending order'), end
n = length(tspan);
ti = tspan(1);
tf = tspan(n);
if n == 2
t = (ti:h:tf)';
n = length(t);
if t(n)<tf
t(n+1) = tf;
n = n+1;
end
else
t = tspan;
end
tt = ti;
y(1,:) = y0;
np = 1;
tp(np) = tt;
yp(np,:) = y(1,:);
i=1;
54 | P a g e
while(1)
tend = t(np+1);
hh = t(np+1) - t(np);
if hh>h
hh = h;
end
while(1)
if tt+hh>tend,hh = tend-tt;end
k1 = dydt(tt,y(i,:),varargin{:})'
ymid = y(i,:) + k1.*hh./2;
k2 = dydt(tt+hh/2,ymid,varargin{:})'
ymid = y(i,:) + k2*hh/2;
k3 = dydt(tt+hh/2,ymid,varargin{:})'
yend = y(i,:) + k3*hh;
k4 = dydt(tt+hh,yend,varargin{:})'
phi = (k1+2*(k2+k3)+k4)/6;
y(i+1,:) = y(i,:) + phi*hh
tt = tt+hh;
i=i+1;
if tt>=tend
break
end
end
np = np+1; tp(np) = tt; yp(np,:) = y(i,:);
if tt>=tf
break
end
end
55 | P a g e