Docsity

MATLAB for Numerical Techniques: A Comprehensive Lab Manual, Lecture notes of Electrical and Electronics Engineering

Toggle sidebar
bg1
Page 1 of 11: Exp. 1 & 2
Bangladesh University of Engineering & Technology
Department of Electrical & Electronic Engineering
EEE 212: Numerical Technique Laboratory
Experiment 1 & 2: Introduction to MATLAB
Objectives:
๏ƒผ
Familiarize with the MATLAB environment.
๏ƒผ
Learn basic syntax and script writing.
๏ƒผ
Explore built-in functions and help features.
๏ƒผ
Perform basic computations and plotting.
Introduction:
MATLAB works with three types of windows on your computer screen. These are the Command
window, the Figure window and the Editor window. The Figure window only pops up whenever you
plot something. The Editor window is used for writing and editing MATLAB programs (called M-files)
and can be invoked in Windows from the pull-down menu after selecting File | New | M-file.
๏ƒ˜ Create a folder of your group name in C drive.
๏ƒ˜ Open MATLAB 6.5. In "current directory'' select your folder.
๏ƒ˜ From the "file" menu start a new m-file. Always write your program in m-file & save it. The
file/function/variable name must start with a letter and cannot contain space. The name can
be a mix of letters, digits, and underscores. (e.g., vector_A, but not vector-A (since "-" is a
reserved char). must not be longer than 31 characters.
๏ƒ˜ You can also write any command or program in "command window".
๏ƒ˜ Function โ€œclear๎˜ƒallโ€ removes all variables, globals, functions and MEX links. Write clear๎˜ƒ
all๎˜ƒat the beginning of your m-file.๎˜ƒ
๏ƒ˜ Write "clc" in command window to clear the command window, "clg" to clear graphics
window. ๎˜ƒ
๏ƒ˜ MATLAB is case sensitive. e.g., NAME, Name, name are 3 distinct variables.
๏ƒ˜ Write "help function_name" in command window after the ">>" sign to see the description
of the function. For example, type "help sin" to know about sin functions in MATLAB. You
can also use help in the menubar.
๏ƒ˜ Explore MATLABโ€™s lookfor and help capability by trying the following:
>>๎˜ƒlookfor๎˜ƒkeywords๎˜ƒ
>>๎˜ƒhelp๎˜ƒ
>>๎˜ƒhelp๎˜ƒplot๎˜ƒ
>>๎˜ƒhelp๎˜ƒops๎˜ƒ
>>๎˜ƒhelp๎˜ƒarith๎˜ƒ
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download MATLAB for Numerical Techniques: A Comprehensive Lab Manual and more Lecture notes Electrical and Electronics Engineering in PDF only on Docsity!

Page 1 of 11: Exp. 1 & 2

Bangladesh University of Engineering & Technology

Department of Electrical & Electronic Engineering

EEE 212: Numerical Technique Laboratory

Experiment 1 & 2: Introduction to MATLAB

Objectives:

๏ƒผ Familiarize with the MATLAB environment. ๏ƒผ Learn basic syntax and script writing. ๏ƒผ Explore built-in functions and help features. ๏ƒผ Perform basic computations and plotting.

Introduction:

MATLAB works with three types of windows on your computer screen. These are the Command window, the Figure window and the Editor window. The Figure window only pops up whenever you plot something. The Editor window is used for writing and editing MATLAB programs (called M-files) and can be invoked in Windows from the pull-down menu after selecting File | New | M-file.

๏ƒ˜ Create a folder of your group name in C drive. ๏ƒ˜ Open MATLAB 6.5. In "current directory'' select your folder. ๏ƒ˜ From the "file" menu start a new m-file. Always write your program in m-file & save it. The file/function/variable name must start with a letter and cannot contain space. The name can be a mix of letters, digits, and underscores. ( e.g., vector_A, but not vector-A (since "-" is a reserved char). must not be longer than 31 characters. ๏ƒ˜ You can also write any command or program in "command window". ๏ƒ˜ Function โ€œclear allโ€ removes all variables, globals, functions and MEX links. Write clear all at the beginning of your m-file. ๏ƒ˜ Write "clc" in command window to clear the command window, "clg" to clear graphics window. ๏ƒ˜ MATLAB is case sensitive. e.g., NAME, Name, name are 3 distinct variables. ๏ƒ˜ Write "help function_name" in command window after the ">>" sign to see the description of the function. For example, type "help sin" to know about sin functions in MATLAB. You can also use help in the menubar. ๏ƒ˜ Explore MATLABโ€™s lookfor and help capability by trying the following:

lookfor keywords help help plot help ops help arith

Page 2 of 11: Exp. 1 & 2

Special Characters:

There are a number of special reserved characters used in MATLAB for various purposes. Some of these are used as arithmetic operators, namely, +, โ€, *, / and . While others perform a multitude of purposes: ๏‚ท % -- anything after % (and until end of line) is treated as comments, e.g.,

x = 1:2:9; % x = [1 3 5 7 9]; ๏‚ท ; -- delimits statements; suppresses screen output, e.g., x = 1:2:9; y = 2:10; % two statements on the same line ๏‚ท ... -- statement continuation, e.g., x = [ 1 3 5 ... 7 9]; % x = [1 3 5 7 9] splitted into 2 lines ๏‚ท : -- range delimiter, e.g., x = [1:2:9]; % x=[1,3,5,7,9] ๏‚ท '-- matrix transposition, e.g., x = [1:2:9]'; % x changed from row vector to column vector if the vector/matrix is complex, โ€œ ' โ€ results in complex conjugation and matrix transposition. ๏‚ท , -- command delimiter, e.g., x = [1:2:9], y = [1:9] % two statements on the same line ๏‚ท : -- precede an arithmetic operator to perform an elemental operation, instead of matrix operation, e.g., x = 3:3: x = 3 6 9

y = 3*ones(3,1)' y = 3 3 3

z = x./y z = 1 2 3

๏‚ท * -- "wild card", e.g.,

clear A* % clears all variables that start with A.

Note that many of these characters have multiple functionalities (function overloading) depending on the context, e.g., "*" is used for scalar multiply, matrix multiply and "wild card" as seen above.

Arithmetic Operations & Built in functions:

Example 1. Find ๐‘ฆ เตŒ ๐‘’๐‘ฅ๐‘แˆบ 5 เฌถ/3 ๐‘๐‘–แˆป

Page 4 of 11: Exp. 1 & 2

z =x./y

๏ƒ˜ Some operations are performed on square matrices only.

๏ƒ˜ + โ€ * / ^ (algebraic/matrix definitions) .+ .โ€ .* ./ .^ (element by element operation) Additionally,

"'" performs matrix transposition; when applied to a complex matrix, it includes elemental conjugations followed by a matrix transposition \ and .\ perform matrix and elemental left division.

Exercise 3. A=[2 3; 4 5]; B=[3 4; 6 7]; Find A+B, AB, A.B, A/B, A\B, A.^2, A./B

Graphics:

MATLAB can produce 2 and 3 dimensional plots_. MATLAB_ is an interactive environment in which you can program as well as visualize your computations. It includes a set of high-level graphical functions for:

๏‚ท Line plots (plot, plot3, polar) ๏‚ท Bar graphs (bar, barh, bar3, bar3h, hist, rose, pie, pie3) ๏‚ท Surface plots (surf, surfc) ๏‚ท Mesh plots (mesh, meshc, meshgrid) ๏‚ท Contour plots (contour, contourc, contourf) ๏‚ท Animation (moviein, movie)

Example 2. x=0:0.1:pi; y=cos(x); plot(y); plot(x,cos(x),'r'); plot(x,y,x,y.^2);

Example 3. x=0:0.1:pi; y=cos(x); plot(y); hold on plot(x,cos(x),'r');

Page 5 of 11: Exp. 1 & 2

Example 4. x=linspace(0,7); y=exp(x); subplot(2,1,1), plot(x,y); subplot(2,1,2), semilogy(x,y);

Example 5. x = magic(3); bar(x); grid

Exercise 4. Plot the following functions in the same window y1=sin x, y2=sin 2x, y3=sin 3x, y4=sin 4x where x varies from 0 to pi.

Loops & Conditionals:

MATLAB has the following flow control constructs: ๏‚ท if statements ๏‚ท switch statements ๏‚ท for loops ๏‚ท while loops ๏‚ท break statements

-1 0 5 10 15 20 25 30 35

-0.

-0.

-0.

-0.

0

1

(^00 1 2 3 4 5 6 )

500

1000

(^10 00 1 2 3 4 5 6 )

10 2

(^01 2 )

1

2

3

4

5

6

7

8

9

Page 7 of 11: Exp. 1 & 2

If the matrices are all of the same size (as is the case here), then the above can be more succinctly written as

A = B + C;

For sufficiently large matrix operations, this latter method is vastly superior in performance.

Example 9. ( break statement )

The break statement lets you exit early from a for or a while loop:

x=โ€10; while x< x=x+2; if x == โ€ 2 break; end end

What is the value of x after execution of the above loop?

Relational Operators

Symbol Meaning <= Less than equal < Less than

= Greater than equal Greater than == Equal หœ = Not equal

Logical Operators

Symbol Meaning & AND | OR หœ NOT

Defining functions:

๏ƒ˜ In MATLAB there is scope for user-defined functions.

Suggestion: Since MATLAB distinguishes one function from the next by their file names, name files the same as function names to avoid confusion. Use only lowercase letter to be consistent with MATLAB's convention.

๏ƒ˜ To define a function, start a new M-file. The first line of M-file should be

function variable_name=function_name(parameters);

Page 8 of 11: Exp. 1 & 2

variable_name is the name of variable whose value will be returned. function_name is user defined according to the rules stated previously.

Example 10. function y=cal_pow(x); y=1+x^2; end

๏ƒ˜ Save this function as cal_pow. ๏ƒ˜ Start another new M-file .This will be our main file. ๏ƒ˜ Write the following commands and run the file:

clear all; x=0:1:3; t=length(x); for i=1:t val(i)=cal_pow(x(i)); end plot(x,val);

Do the following:

Exercise 5. Write a program to compute the variance of an array x. The variance ๐œŽ is defined to be:

๐œŽ เตŒ

เฏ‡

เฏœเญ€เฌต

where ๐‘ฅฬ… is the average of the array x. a) For x , use all the integers from 1 to 1000. b) Create x by built in function rand.

Exercise 6. Define the matrices

A=[17 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] B=[ 2 3 4 5 ; 6 7 8 9 ; 10 11 12 13 ; 14 15 16 17 ] C=[ 1 2 3 ; 4 5 6 ; 7 8 9 ] y=[ 4 3 2 1 ]'

Note the transpose ' on the y-vector which makes y a column vector. a) Compute AB and BA. Is matrix multiplication commutative? b) Compute AC. Why do you get an error message? c) Solve the following system of equations:

(^10) 0.5 1 1.5 2 2.5 3

2

3

4

5

6

7

8

9

10

Page 10 of 11: Exp. 1 & 2

Empirical formulas for finding ๐‘ต and ๐œท : If the transition width (normalized) and stop band attenuation are ฮ”๐œ” and ๐›ฟ respectively then ๐ด เตŒ เต†20logแˆบ๐›ฟแˆป

Here ๐‘ should be of integer type. See what does built in MATLAB function ๐‘“๐‘™๐‘œ๐‘œ๐‘Ÿ do.

0.5842แˆบ๐ด เต† 21 แˆป เฌด.เฌธ^ เต… 0.07886แˆบ๐ด เต† 21 แˆป, 21 เต‘ ๐ด เต‘ 50

The impulse response, โ„Ž (^) เฎฝ แˆบ๐‘›แˆป for low pass filter is given below:

sin แ‰†แ‰€๐‘› เต†

2 แ‰^2 ๐œ‹๐‘“เฏ–^ แ‰‡

2 แ‰^2 ๐œ‹๐‘“เฏ–

Design a linear phase low pass FIR filter using the Kaiser window to satisfy the following amplitude response specifications:

Sampling frequency, ๐นเฏฆ 1 kHz

Ideal cutoff frequency, ๐นเฏ– 250 Hz

Transition width, ฮ”๐น 50 Hz

Pass band ripple, ๐›ฟ 0.

a) Write M-file to plot impulse response โ„Žแˆบ๐‘›แˆป เตŒ โ„Žเฎฝ แˆบ๐‘›แˆป โ‹… ๐‘คแˆบ๐‘›แˆป vs. ๐‘› of the filter.

b) Plot magnitude (in dB) and phase response (in degrees) vs. analog frequency. To do this necessary codes are given at the end of this sessional sheet.

N.B.

๐‘“เฏ– เตŒ

Fเญฑ

Follow the algorithm below to write the codes for Kaiser Window FIR low pass filter impulse response:

Page 11 of 11: Exp. 1 & 2

  1. Enter the inputs ๐นเฏฆ, ๐นเฏ–, ฮ”๐น, ๐›ฟ and L (^) m.
  2. Evaluate ๐‘“เฏ–, ฮ”๐œ”, ๐ด, ๐‘, ๐›ฝ, ๐›ผ and ๐ผเฌด แˆบ๐›ฝแˆป. Create a matlab subprogram to calculate ๐ผเฌด แˆบ๐›ฝแˆป as calculation of zero order modified Bessel function of the first kind will be needed several times.
  3. For each value of ๐‘›, evaluate

เฌถ เต 

เฌต/เฌถ , ๐‘คแˆบ๐‘›แˆป and โ„Žเฎฝ แˆบ๐‘›แˆป. Now calculate โ„Žแˆบ๐‘›แˆป

  1. Now make a plot โ„Žแˆบ๐‘›แˆป.

%%%finding filter magnitude and phase response in frequency domain Page 11 of 11:Expt 1 & 2 NFFT=1024; hfir=fft(hFIR,NFFT); %%%%% hFIR=calculated h(n) earlier k=0:NFFTโ€1; %waxis=2pi1/NFFT.k; faxis=1/NFFT.k; magresdB=20log10(abs(hfir)); subplot(312),plot(faxis(1:NFFT/2+1)Fs,magresdB(1:NFFT/2+1)) grid on; xlabel('Frequency (Hz)') ylabel('Magnitude response (dB)') subplot(313),plot(faxis(1:NFFT/2+1)Fs,(unwrap(angle(hfir(1:NFFT/2+1)))) 0/pi) grid on; xlabel('Frequency (Hz)') ylabel('Phase response (degrees)') %%%finding magnitude and phase response by freqz built in function % figure % freqz(hFIR,1);

Reference Books:

  1. Mathews, J. H., & Fink, K. D. (2004). Numerical Methods using MATLAB (4th ed.). Upper Saddle River, NJ: Pearson Prentice Hall.
  2. Etter, D. M. (2005). Engineering Problem Solving with MATLAB (3rd ed.). Upper Saddle River, NJ: Pearson Prentice Hall.

Revised by,

Md. Samrat

(April 2025)

Page 2 of 7: Exp. 3

For example, suppose we have a table like this, which gives some values of an unknown function ๐‘“. The data are given in the table:

Table 1

๐’™ ๐’‡แˆบ๐’™แˆป 0 0 1 0. 2 0. 3 0. 4 -0. 5 -0. 6 -0.

The plot can be shown as: .

What value does the function have at, say, x = 2.5? Interpolation answers questions like this.

Types of interpolation:

A. Linear interpolation

One of the simplest methods is linear interpolation. Consider the above example of determining ๐‘“แˆบ2.5แˆป

. We join the data points by linear interpolation and get the following plot:

Page 3 of 7: Exp. 3

Noe we can get ๐‘“แˆบ2.5แˆป. Since 2.5 is midway between 2 and 3 , it is reasonable to take ๐‘“แˆบ2.5แˆป midway between ๐‘“แˆบ 2 แˆป เตŒ 0.9093 and ๐‘“แˆบ 3 แˆป เตŒ 0.1411 , which yields 0.5252.

Generally, linear interpolation takes two data points, say ( x a , ya ) and ( x b , y b ), and the interpolant is given by

This formula can be interpreted as a weighted mean.

Linear interpolation is quick and easy, but it is not very precise.

Exercise 2. Plot the curve corresponding to table1 using linear interpolation.

Exercise 3. y = sin(x) ; x = 0:10; x(i) = 0 : 0.25 :10; Construct the interpolant y and plot.

A. Polynomial interpolation

Polynomial interpolation is a generalization of linear interpolation. Note that the linear interpolant is a linear function. We now replace this interpolant with a polynomial of a higher degree.

Consider again the problem given above. The following sixth-degree polynomial goes through all seven points:

๐’‡แˆบ๐’™แˆป เตŒ เต†๐ŸŽ. ๐ŸŽ๐ŸŽ๐ŸŽ๐Ÿ๐Ÿ“๐Ÿ๐Ÿ๐’™๐Ÿ”^ เต† ๐ŸŽ. ๐ŸŽ๐ŸŽ๐Ÿ‘๐Ÿ๐Ÿ‘๐ŸŽ๐’™๐Ÿ“^ เต… ๐ŸŽ. ๐ŸŽ๐Ÿ•๐Ÿ‘๐Ÿ๐Ÿ๐’™๐Ÿ’^ เต† ๐ŸŽ. ๐Ÿ‘๐Ÿ“๐Ÿ•๐Ÿ•๐’™๐Ÿ‘^ เต… ๐ŸŽ. ๐Ÿ๐Ÿ๐Ÿ“๐Ÿ“๐’™๐Ÿ^ เต… ๐ŸŽ. ๐Ÿ—๐ŸŽ๐Ÿ‘๐Ÿ–๐’™

Substituting x = 2.5, we find that f (2.5) = 0.5965.

Page 5 of 7: Exp. 3

Above figure shows Lagrange interpolation of the bell curve function ๐‘“แˆบ๐‘ฅแˆป เตŒ ๐‘’เฌฟ เฏซ^

เฐฎ for three different polynomial degrees: N = 5, 9, and 15. as N increases, the interpolation fits the central region better. However, for N = 15 , significant oscillations appear near the edges (Rungeโ€™s phenomenon).

Algorithm for the Lagrange Polynomial: To construct the Lagrange polynomial

of degree n, based on the n+1 points for. The Lagrange coefficient polynomials for degree n are:

for.

So, for a given x and a set of (N+1) data pairs, ( x (^) i , f (^) i ), i = 0, 1, .................N:

1 Read N, x(0:N), f(0:N), x_val 2 sum โ† 0 3 for i = 0 to N do 4 p โ† 1 5 for j = 0 to N do 6 if j โ‰  i then 7 p โ† p * (x_val - x(j)) / (x(i) - x(j)) 8 endif 9 endfor

-5 -4 -3 -2 -1 0 1 2 3 4 5 x

-0.

0

1

2

2.5 Lagrange Interpolation for Bell Curve f(x) = e^

-x 2

Original Function e -x^2 Lagrange N= Points N= Lagrange N= Points N= Lagrange N= Points N=

Page 6 of 7: Exp. 3

10 sum โ† sum + p * f(i) 11 endfor 12 result โ† sum 13 Write result

Exercise 4. Write a MATLAB program implementing Lagrange Polynomial.

Exercise 5. Construct a Lagrange interpolating polynomials for the data points given in table 1.

a. Newton polynomial:

To construct and evaluate the Newton polynomial of degree ๏‚ฃ n that passes through the n ๏€ซ 1 points ( x (^) k , y (^) k ) ๏€ฝ ( x (^) k , f ( x (^) k )) for k ๏€ฝ 0,1,โ€ฆโ€ฆ n :

This polynomial P n (x) is said to be a Newton Polynomial with n centers x 0 , x 1 to x n-1. It involves sums

of products of linear factors upto

a (^) n (x-x 0 )(x-x 1 )(x-x 2 )โ€ฆ ................................ (x-xn-1 )

Construction for n = 1.

Use the two points.

Algorithm Newton polynomial:

To construct and evaluate the Newton polynomial of degree ๏‚ฃ n that passes through the n ๏€ซ 1 points ( x (^) k , y (^) k ) ๏€ฝ ( xk , f ( x (^) k )) , for k ๏€ฝ 0,1,โ€ฆโ€ฆโ€ฆ n :

where

So for a given set of (N+1) data pairs, ( x (^) k ,y (^) k ), k = 0 to N