70
Information Technology Solutions Lab Manual ISC 210 Computational Methods Prepared by Dr. Jehad Al-Dallal Latifa Al-Dhaferi Revised Spring 2015-2016 Kuwait University College of Computing Sciences and Engineering Department of Information Science

Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

Embed Size (px)

Citation preview

Page 1: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

Information Technology Solutions

Lab Manual

ISC 210 Computational

Methods

Prepared by

Dr. Jehad Al-Dallal

Latifa Al-Dhaferi

Revised Spring 2015-2016

Kuwait University

College of Computing Sciences and Engineering

Department of Information Science

Page 2: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 2

Table of Contents Laboratory Hardware and Software/Tools Requirements ................................................................................... 5

Laboratory Schedule .................................................................................................................................................. 6

Laboratory Policy ........................................................................................................................................................ 7

Laboratory Grading Policy ......................................................................................................................................... 8

Introduction .................................................................................................................................................................. 9

Familiarity with Lab Hardware and Software tools ................................................................................................. 9

Laboratory Tools Setup .............................................................................................................................................. 9

Laboratory #1 –Introduction to MATLAB .............................................................................................................. 24 Laboratory #2 –Introduction to Script Files and Matrices .................................................................................. 29 Laboratory #3 –Functions in MATLAB ................................................................................................................... 34 Laboratory #4 –If statement and For loop ............................................................................................................. 38 Laboratory #5 –Solving Linear Systems in MATLAB .......................................................................................... 44 Laboratory #6 –Polynomials .................................................................................................................................... 50 Laboratory #7 – Eigenvalues and Eigenvectors ................................................................................................... 55 Laboratory #8 –Interpolation ................................................................................................................................... 58 Laboratory #9 –Least Squares Regression ................................................................................................ 61 Laboratory #10 –Root Finding Methods ................................................................................................................ 67 Appendix A: Rules to fallow by Computer Lab Users.......................................................................................... 71

Appendix B: Endorsement ....................................................................................................................................... 70

Page 3: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 3

Laboratory Hardware and Software/Tools Requirements

In this lab the students will be using MATLAB application software run on a PC with

Windows operating system.

Page 4: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

Laboratory Schedule

# Lab Title Lab activity

1 Introduction to MATLAB

2 Introduction to MATLAB Quiz#1

3 Introduction to Script Files and Matrices

4 Introduction to Script Files and Matrices Quiz#2

5 Functions in MATLAB

6 Functions in MATLAB

7 If statement and For loop

8 Solving Linear Systems in MATLAB Quiz#3

9 Polynomials

10 Eigenvalues and Eigenvectors Quiz#4

11 Interpolation

12 Least Squares Regression

13 Least Squares Regression Quiz#5

14 Root Finding Methods

15 Root Finding Methods Quiz#6

Page 5: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 5

Laboratory Policy

Fallow the laboratory rules listed in appendix “A”

Cheating in whatever form will result in F grade.

Attendance will be checked at the beginning of each Lab.

Number of absence hours will be combined with the absence hours of the course and they

are subject for applying the university absence regulations.

Cheating in Lab Work or Lab Project will result F grade in Lab.

There will be no make-up for any Quiz/Exam/Lab.

Hard work and dedication are necessary ingredients for success in this course.

Page 6: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 6

Laboratory Grading Policy

Activity Weight

Lab Quizzes 10%

Page 7: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 7

Introduction This lab is an integral part of the course ISC 210 Computational Methods. The main

objectives of the lab are to experience using MATLAB to apply the numerical methods

taught in the class.

Familiarity with Lab Hardware and Software tools In this lab the students will be using MATLAB.

Laboratory Tools Setup

MATLAB R2007a is the software that will be used. In the following steps we will describes how to install

and activate MathWorks™ products on a computer running the Microsoft® Windows

® operating system (32-

bit or 64-bit).

Step 1: Start the Installer

Insert the DVD into the DVD drive connected to your system or double-click the installer file you

downloaded from the MathWorks Web site. The installer should start automatically.

If you do not have an Internet connection, select the Install without using the Internet option and click

Next.

Page 8: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 8

Step 2: Review the License Agreement

Review the software license agreement and, if you agree with the terms, select Yes and click Next.

After the installation is complete, you can view or print the license agreement using the file license.txt

located in the top-level installation folder.

Page 9: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 9

Step 3: Specify the File Installation Key

If you do not have an Internet connection, and choose to install manually, the installer displays the File

Installation Key dialog box. A File Installation Key identifies the products you can install.

If you have the key, select the I have the File Installation Key for my license option, enter the File

Installation Key, and click Next. The administrator contact on a license can retrieve the File Installation Key

from the License Center at the MathWorks Web site.

If you do not have the key, select the I do not have the File Installation Key option and click Next. The

installer will provide you with the information you need to get a key.

Page 10: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 10

If You Do Not Have the File Installation Key

If you choose the I do not have the File Installation Key option, the installer displays the Installation and

Activation Next Steps dialog box. This dialog box contains the information you need to retrieve your File

Installation Key from the License Center at the MathWorks Web site, including:

Host ID

Release number (e.g., R2010a)

Operating system user name (Note that user names are case-sensitive in activation.)

Save the information displayed in this dialog box. For example, you can print a copy by clicking Print. Take

the information to a computer with an Internet connection and visit the License Center at the MathWorks

Web site. The MathWorks uses this information to generate a File Installation Key and a License File. You

must have this information with you when you return to the computer on which you want to install and

activate the software. To exit the activation process, click Finish.

Page 11: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 11

Step 4: Choose the Installation Type

In the Installation Type dialog box, specify whether you want to perform a Typical or Custom installation

and click Next.

Choose Typical if you have an Individual or Group license and do not need to specify which products you want to install and do not need to access any installation options.

Choose Custom if you need to specify which products to install, need access to installation options, or need to install the license manager (network license options only).

Page 12: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 12

Step 5: Specify the Installation Folder

Specify the name of the folder where you want to install MathWorks products. You can accept the default

installation folder or specify the name of a different installation folder. If the folder doesn't exist, the installer

creates it.

When specifying a folder name, do not specify a name that contains the @ sign, an exclamation point (!),

the percent character (%), the plus sign (+), or the dollar sign character ($). The full path of the installation

folder must not include a folder named private. If you make a mistake while entering a folder name and

want to start over using the default folder name, click Restore Default Folder. To continue with the

installation, click Next.

Page 13: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 13

Step 6: Specify Products to Install (Custom Only)

If you are performing a custom installation, you can specify which products you want to install in the

Product Selection dialog box. This dialog box lists all the products associated with the license you selected

or with the Activation Key you specified. In the dialog box, all the products are preselected for installation. If

you do not want to install a particular product, clear the check box next to its name.

After selecting the products you want to install, click Next to continue with the installation.

Page 14: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 14

Step 7: Specify Installation Options (Custom Only)

For Custom installations, you can specify several installation options, including:

Setting the permissions of all installed files to read only.

Determining whether the installer puts shortcuts for MATLAB software in the Start menu and on the desktop.

Specifying which files the operating system associates with MATLAB, based on their file extension. For example, if you associate files with the .m file extension with MATLAB, the operating system identifies the type of these files as MATLAB M-file. The installer preselects the extensions associated with products you are installing.

After selecting installation options, click Next to proceed with the installation.

Page 15: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 15

The following table provides brief descriptions of these file extensions.

File Extension Description

.ctfx MATLAB Compiled Application

.fig MATLAB Figure

.m MATLAB Code

.mat MATLAB Data

.mdl Simulink Model

.mdlp Simulink Protected Model

.mex* MATLAB MEX. This extension is platform specific: .mexw32 or .mexw64

.mn MuPAD Notebook

.mu MuPAD Code

.muphlp MuPAD Help

.p MATLAB P-code

.ssc Simscape Model

.xvc MuPAD Graphics

.xvz MuPAD Graphics

Page 16: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 16

Step 8: Confirm Your Choices and Begin Copying Files

Before it begins copying files to your hard disk, the installer displays a summary of your installation

choices. To change a setting, click Back. To proceed with the installation, click Install.

As it copies files to your hard drive, the installer displays a status dialog box to show the progress of the

installation.

Step 9: Complete the Installation

When the installation successfully completes, the installer displays the Installation Complete dialog box. In

this dialog box, you can choose to activate the software you just installed. You cannot use the software you

installed until you activate it. The MathWorks recommends activating immediately after installation. If you

logged in to your MathWorks Account during installation, your log-in session continues into the activation

process. Click Next to proceed with activation.

If you choose to exit the installer without performing activation, clear the Activate MATLAB option and

click Finish (the button label changes). You can activate later using the activation application.

Page 17: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 17

Step 10: Activate Your Installation

Because you were not logged in to your MathWorks Account during installation, or you started the

activation application independently, you must choose whether to activate automatically or manually.

Select the Activate manually without the Internet option and click Next.

Page 18: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 18

Step 11: Specify the Path to the License File

To activate without an Internet connection, you must have a License File. The License File identifies which

products you can run. The administrator contact on the license can retrieve the License File from the

License Center at the MathWorks Web site.

Select the Enter the path to the License File option and enter the full path of your License File in the text

box (or drag and drop the file) and click Next. If you do not have your License File, select the I do not

have a license file option.

Page 19: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 19

If You Do Not Have a License File

If you are activating manually and do not have your License File, the License File Retrieval dialog box explains

how to get your License File and finish activation. The dialog box displays the information you will need to get

your License File, including:

Host ID

Release number (e.g., R2010a)

Operating system user name (Note that user names are case-sensitive in activation.)

Save the information displayed in this dialog box. For example, you can print a copy by clicking Print. Take

the information to a computer with an Internet connection and visit the License Center at the MathWorks Web

site. The MathWorks uses this information to generate a File Installation Key and a License File. You must

have this information with you when you return to the computer on which you want to install and activate the

software. To exit the activation application, click Finish.

Note Your installation will not be activated. You cannot run MATLAB until you retrieve your License File.

Page 20: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 20

Step 12: Complete the Activation

After activating your installation, you can run The MathWorks software. If you do not want to run MATLAB

now, clear the Start MATLAB option and click Finish to exit the activation process.

Page 21: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 21

Reference: The Math Works - http://www.mathworks.com

Page 22: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 22

Laboratory #1 – Introduction to MATLAB

1. Laboratory Objective

The objective of this introductory laboratory is to introduce some of the basic commands in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Know how to enter/exit the MATLAB environment. b. Write Formulas and Expressions in MATLAB. c. Create, modify, access elements and do basic operations on vectors and matrices in MATLAB. d. Write and evaluate formulas and equations using MATLAB. e. Manipulate vectors using MATLAB.

3. Laboratory Introductory Concepts

MATLAB is high-performance language for � technical computing � integrates computation, � visualization, � programming

in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation The name of MATLAB stands for Matrix Laboratory,

� All operations are assumed to be done on matrices unless you specifically state otherwise. MATLAB is an interactive system. � Allows you to solve many technical computing problems, especially those with matrix and vector formulations.

Getting Started On your Windows desktop, double-click the MATLAB shortcut icon to start MATLAB program. � To end your MATLAB session, select Exit MATLAB from the File menu or type quit or exit in the Command Window.

Page 23: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 23

Command Window Used to enter the statements (Commands) and get the output

� The prompt (>>) indicates MATLAB is ready to accept commands from you MATLAB As a Calculator The basic arithmetic operators are + - * / ^ Variables

� An ―equals‖ sign is used to make an assignment � MATLAB does not require any type declarations or dimension statements. � Variable names consist of a letter, followed by any number of letters, digits, or underscores. � MATLAB is a case sensitive. � The default variable is ―ans‖

Semicolon

� in MATLAB the semicolon serves to suppress the output of the line that it concludes. � If a statement is not terminated with a semicolon, then the result of the statement is displayed.

Page 24: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 24

Some useful command

� who – lists the variables in the current workspace. � clear all– removes variables from the workspace. � clc – clears all input and output from the Command Window display, giving you a "clean screen."

Vector

� Refers to a one dimensional (1×N or N×1) matrix Method 1: defined by placing a sequence of numbers within square braces >> x = [1 2 3 4] >> y = [1,3,5,6,7] >> z = [3 -21 5 6]'

Method 2: using a set of numbers with a common increment using colons : Syntax: start:increment(step):end >> w = [2:0.25:4] >> t = [9:-2:1] Method 3: using the linspace function generates row vectors with equally spaced elements Syntax: linspace(firstValue,lastValue,numValues) >> evens = linspace(0,10,6) >> v = linspace(1,2,5)

Accessing elements within a vector � You can view individual entries in a vector >> v(2) � You can also look at specific parts of vector >> v(1:3)

Vector Operation

� All the operators in MATLAB defined on vectors : +, -, *, /, ^, etc. >> t – v >> evens^2 >> evens.^2 >> t*v >> t.*v � To sum all the elements in a vector >> sum(v) � To find number of elements in a vector

Page 25: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 25

>> n = length(v) � Creates a matrix with specified values on a diagonal >> diag(x)

Examples:

x=[2 6 7] - create a row vector x=[x 8] - add another element to x x=[2 ; 6 ; 7 ] - create a column vector x=1:6 - create a vector with elements 1, 2, 3 ...6 x=1:0.5:6 - create a vector with elements 1, 1.5, 2, 2.5 ... 6 x=linspace(1,6,11) - create a row vector with 11 equally spaced elements

running from 1 to 6 x=ones(4,5) - create a matrix full of 1s with 4 rows and 5 columns x=1:3; y=4:6; z=[x y] - join 2 vectors

4. Laboratory Problem Description

In this laboratory, you are required to write a MATLAB command to describe

variables:

>> x = 2 >> y = x+3 >> 1+5 >> z = ans + 4 >> a = 2 >> b = 4; >> b Write a MATLAB command for the following operations:

2*2

653

2

8*443

Write the MATLAB command(s) to

1. Find the sum of all even number between 2 and 100 2. Create a column vector with 11 equally spaced points in the interval [0,1] 3. Create vector B= [-3 -6 -9 ... -24]

Page 26: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 26

5. Laboratory Exercises

Ex1: Write a MATLAB command for the following operations:

212

62

75

5*123.04 3 pi

Ex2: Let x = [3 2 6 8]' and y = [4 1 3 5]' (Note: x and y should be column vectors).

1. Raise each element of x to the power specified by the corresponding element in y. 2. Divide each element of y by the corresponding element in x

Ex3: Write the use of the following MATLAB commands:

who : ………………………………………………………………………..

clc : ………………………………………………………………………..

Page 27: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 27

Laboratory #2 –Introduction to Script Files and Matrices

1. Laboratory Objective

The objective of this laboratory is to show the use of scripts files and matrices in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Use format command to format output b. Compute mathimatical functions c. Know how to Open, create, save, and run Scripts Files. d. Construct a matrix e. Modify, access elements and do basic operations on matrices.

3. Laboratory Introductory Concepts Format

� To set display format for output Example:

>>format short Scaled fixed point format, with 4 digits after the decimal point. For example, 3.1416. >>format long Scaled fixed point format with 14 to 15 digits after the decimal point. For example, 3.141592653589793. >>format rat Ratio of small integers. For example, 355/113

Page 28: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 28

Mathematical MATLAB Functions

cos(x) Cosine of x sin(x) Sine of x tan(x) Tangent of x sqrt(x) Square root of x abs(x) Absolute value of x exp(x) Exponential of x log(x) Log to the base e of x

Example:

>>cos(pi) ans = -1 >> sin(pi/2)+cos((3*pi)/2) ans = 1.0000 >>sqrt(25) ans = 5

Scripts

� Text files containing a sequence of normal MATLAB commands/statements. � run much as if you were typing the program statements in the command window. � The values of all variables are retained in memory and are accessible even after the program has run. � Save the file under a name that ends in m � To create or modify program files use the MATLAB editor. � To start the MATLAB editor window from the main MATLAB window select New and then M-file from the File pull down menu in the desktop window � To edit an existing file select open and select the appropriate file or enter edit followed by the file name. � You can run a script by typing the name of its file (without the .m suffix) in the MATLAB command window. � For example, if your program is stored in the file myprogram.m then you run it by entering >> myprogram

Page 29: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 29

Example

%This is my first script A=[4 1 2 3 0] B=linspace(1,2,5) C=A.*B C A. D=B.^A

Matrices A matrix generally refers to a 2-dimensional array, i.e. an m×n array where m and n are greater than 1

� MATLAB allow you to build matrices of your own with any entries that you may want � You only have to follow a few basic conventions: � Separate the elements of a row with blanks or commas. � Use a semicolon ‗ ; ‗ to indicate the end of each row. � Surround the entire list of elements with square brackets, [ ]. � Try the following

>> A = [1 2 3; 4 4 3; 2 2 4] >> B = [ 1 2 3 4 4 3 2 2 4] >> C [ 1, 2, 3; 4 4 3 2 2 4]

Special Matrices

� Create nxn matrix of random elements >> a = rand(n)

� Create mxn matrix of random elements >> b = rand(m,n)

� Create an mxn matrix with each element is 1 >> c = ones(m,n)

� Create an mxn matrix with each element is 0 >> d = zeros(m,n)

� Create nxn identity matrix >> f = eye(n) Accessing elements within a matrix

� You can view individual entries in a matrix >> A(1,2)

Page 30: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 30

� You can also look at specific parts of a matrix >> A(1:3,:) >> A(:,1) % whole column >> A(1,:) % whole row

Matrix Operations

� All the operators in MATLAB defined on matrices : +, -, *, /, ^, sqrt, etc.

>>A+B >>A*B

� Transpose of matrix is defined as follow >> A‘

� To find size of elements in a matrix >> [m,n] = size(A)

Matrix Functions

sum(data) - sums each column. mean(data) - finds the mean of each column max(data) - finds the maximum number in each column

4. Laboratory Problem Description

In this laboratory you are required to write a MATLAB command for:

)2

sin(

, )90cos( , 144 , 101

In addition, you have to solve the following problem:

Let A= [2 9 0 0 ; 0 4 1 4 ; 7 5 5 1 ; 7 8 7 4] and b= [ -1 ; 6 ; 0 ; 9] and a= [ 3 -2 4 -5] Find the following:

a. Multibly A by b b. Add 4 to vector a c. Multibly a by b d. Multiply A by the inverse a e. Find the square of A f. Raise A to the power of 2 g. Find rows 2 and 3 in matrix A.

Page 31: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 31

Given the matrix

953

276

142

A Provide the command needed to

a. Assign the first row of A to a vector called x b. Assign the last 2 columns of A to a matrix called y c. Add 6 to each element of A d. Find the sum of all elements in x e. Find the square of all elements in y f. Save all commands in a script file mat.m and run the script from command window.

5. Laboratory Exercises

Ex1: Write a MATLAB command for the following operations and format the output to

be short:

5*2

6)

3sin(

7

)cos(*123.04)9( 3 sqrt

Ex2: Let

142

793

201

A and

4420

168

1602

B Find the following:

1. A transpose 2. A + B 3. Multibly A by 0.5 4. Devide B by 2 5. Find the square of A 6. Raise B to the power of -1

EX3: Use rand function to create a 9x8 matrix. Then answer the following:

a. Make a matrix that is the transpose of the original matrix b. Assign the row 8 of the original matrix to a vector called b c. Assign the columns 1 and 2 of the original matrix to a matrix called c d. Write all commands in a sript file name it EX3.m and run it from command window.

Page 32: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 32

Laboratory #3 – Functions in MATLAB

1. Laboratory Objective

The objective of this introductory laboratory is an introduction to graphics (ploting) and functions in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Demonstrate 2D graphs using MATLAB b. Use MATLAB editor to Open, create, save, and run functions

3. Laboratory Introductory Concepts Graphics: Plot

� Two-dimensional line plot is created with the plot command. � Syntax: plot(xdata,ydata) � where xdata and ydata are vectors containing the data. � Note that xdata and ydata must be the same length and both must be the same type i e both type, i.e., must be either row or column vectors. � The MATLAB commands to create a simple plot of y = sin(3*pi*x) from 0 to 2*pi.

>> x = 0:pi/30:2*pi; % x vector, 0 <= x <= 2*pi, % increments of pi/30

>> y = sin(3*x); % vector of y values >> plot(x,y) % create the plot

� Multiple x-y pairs create multiple graphs with a single call to plot.

>> x = 0:pi/30:2*pi; >> y = sin(3*x); >> y2= sin(3*x-0.2); >> y3= sin(2*x); >> plot(x,y,x,y2,x,y3)

� To graph the piecewise function,

03

30)(

2

xx

xxxf

� you must define two intervals x1 and x2. � Each function must be defined in terms of its interval

Page 33: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 33

Function Functions are m-files that takes certain inputs and return certain outputs p. The first line of a function must be of the form

function [outputs]=functionname(inputs)

where:

� outputs stands for any outputs that the function should return. � Inputs stands for any variable or values that need to be used as inputs for the m-file. � Inputs and outputs are comma-separated lists of variable names � The name of the M-file and of the function should be the same � The name of an M-file begins with an alphabetic character and has a filename extension of .m.

Example 1

function y=f1(x) y=2*x.^3-3*x+1;

Example 2

function [s,p] = addmult(x,y) %This is addmult.m Compute sum and %product of two matrices

s=x+y; p=x*y;

How to call a function?

� Function calls written in function syntax � enclose the input argument list in parentheses parentheses, � separate the inputs with commas, � enclose string arguments with single quotation marks, � and optionally assign any output from the function to one or more output arguments. � Unlike command syntax, there are no limitations on when you can use function syntax in a function call.

Example 1

Try the following:

>>f1(2) >>y=f1(3) >> x=1 >>y=f1(x)

Page 34: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 34

Example 2 How to call the addmult if the inputs : 1. 2, 4 2. [1 2; 3 4] , [2 2; 1 1] 3. [1 2 3]; [1 0 1]

4. Laboratory Problem Description

In this laboratory you are required to plot the following function for -2 ≤ x ≤ 2 using

100 equally spaced points.

otherwise

xe

x

f x

0

1

1x01

2

In addition, you have to solve the following problem:

Write a MATLAB function that find the absolute value of any input number x.

Write MATLAB function to solve the equation ax2 + bx + c = 0. The output should be the two roots, and the input shall be a, b, c

a

acbbx

2

42

1

a

acbbx

2

42

2

Test your function with the following values a. a=2, b=3, c=1 b. a=1, b=4, c=0.5

Page 35: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 35

5. Laboratory Exercises

Ex1: Write MATLAB commands to create a simple plot of y = sin(3*pi*x)

from 0 to 2*pi.

Ex2: Giving that 1)( 2 xxf plot the function in [-4,4]

Ex3: Write a MATLAB function SurfaceA to compute the surface area of sphere with

radius r where :

Surface Area = 4 π r2

Sample output for radius r = 3

>>SurfaceA(3)

ans =

113.0973

Ex4: Write a MATLAB function probA which take the value of x and y as inputs

and calculate the a and b according to the following formula

)sin()cos(

2 2

yxb

yxa

Test your function for x=2 and y=3

Page 36: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 36

Laboratory #4 – If Statement and For loop

1. Laboratory Objective

The objective of this laboratory is to introduce input command, IF Statement and For loop in MATLAB.

2. Laboratory Learning Outcomes: By completing this laboratory students will be able to:

a. Request user input b. Describe relational and logical operations c. Apply and know how to use if statement in MATLAB d. Apply and know how to use for loop statement in MATLAB

.

3. Laboratory Introductory Concepts

input - Request user input

Syntax

evalResponse = input(prompt) strResponse = input(prompt, 's')

evalResponse = input(prompt)

Displays the prompt string on the screen, waits for input from the keyboard,

evaluates any expressions in the input, and returns the value in evalResponse.

To evaluate expressions, the input function accesses variables in the current

workspace.

strResponse = input(prompt, 's')

Returns the entered text as a MATLAB string, without evaluating expressions.

Example Write a MATLAB command to read a vector X >>X = input('Enter Vector X:')

Enter Vector X:[1 2 3] X = 1 2 3

Page 37: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 37

Relational Operators

Logical Operator

Page 38: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 38

If Statement

Syntax:

if statement, condition.

� The general form of the IF statement is

if expression statements elseif expression

tatements else

statements End

Example1 x = input(' Type x : ') if (x<0)

disp('x is negative') else

disp('x is non-negative') end Example2 function b=even(n) % b=even(n). If n is an even % integer, then b=1 otherwise, % b=0. if (mod(n,2)==0) b=1; else b=0; end

Page 39: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 39

For Loops FOR Repeat statements a specific number of times. Syntax: for variable = 1:n, statement, ..., end Example 1

function S=mySum(a) N=length(a) S=0 for i=1:N, S=S+a(i) end

Example 2: Create a Hilbert matrix using nested for loops:

k = 10; hilbert = zeros(k,k); % Preallocate matrix for m = 1:k for n = 1:k hilbert(m,n) = 1/(m+n -1); end end

Page 40: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 40

4. Laboratory Problem Description

In this laboratory you are required to trace the following scripts and write the output:

% If Statement

bal = input('type balance: ')

if (bal < 5000)

rate = 0.03

elseif (bal < 10000)

rate = 0.0325

else

rate = 0.035

end

% computes the sum of the series

%

% 1 - 1/2 + 1/3 - 1/4 + ...

%

N = input('type the number of terms to be added up: ') % asks the user to provide a value for

N

sign = 1; % initialise the sign for the term 11

sum_series = 0; % initialise the sum of the series

for n = 1:N

sum_series = sum_series + sign/n;

sign = -sign; % changes sign for alternating

series

end

sum_series % prints out the sum of the series to N terms

In addition, Write a MATLAB Function to build the 3 by 4 matrix B with entries

1

2,

jib ji

Page 41: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 41

5. Laboratory Exercises

Ex1: Write a MATLAB function to input an integer n and build the n by n matrix A

with entries aij = 2ij

Ex2: Write a MATLAB function Grad that takes student MT1 ,MT2 out of 25 and Final

out of 50 as input and calculate Total out of 100 and return the Grade as output

according to the following scale:

> = 90 A

> = 80 B

> = 70 C

> = 60 D

Else F

Sample output for radius MT1 = 22 , MT2 = 23 Final = 45

>>grad(22,23,45)

Total =

90

Grade =

A

Ex3: Write a MATLAB function fact that read N as input from user and compute N!

(Hint : N! = 1X2X….XN)

Page 42: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 42

Laboratory #5 – Solving Linear Systems in MATLAB

1. Laboratory Objective

The objective of this introductory laboratory is to introduce how to solve linear systems in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Know how to use syms command b. Compute the solution of a system of linear equation using

o Left division

o Gauss-Seidel method

c. Compute Vector and matrix norms d. Compute the LU factorization (L, U, P) of a matrix

3. Laboratory Introductory Concepts

sym

Symbolic numbers, variables, and objects

Syntax

S = sym(A) x = sym('x') x = sym('x', 'real')

Description

S = sym(A) constructs an object S, of class 'sym', from A. If the input argument is

a string, the result is a symbolic number or variable. If the input argument is a

numeric scalar or matrix, the result is a symbolic representation of the given

numeric values.

x = sym('x') creates the symbolic variable with name 'x' and stores the result in x.

x = sym('x', 'real') also assumes that x is real

Solving Linear Systems

Suppose we want to solve the linear system x – 2y + z = 0 2y – 8z = 8 -4x + 5y + 9z = -9

Page 43: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 43

We can solve this system in several ways in MATLAB; you will learn two of them in this part and another in the next part.

First we need to save the coefficients of the system in a matrix, and the right-hand side vector in another matrix. Enter A = [1 -2 1 0 2 -8 -4 5 9] b = [0; 8; -9] and then enter X = A\b % left division The three numbers you see are the solution values of x, y, and z.

Example: >> A=[4 -1 1;2 5 2;1 2 4] >> b=[8 3 11]' >> x=A\b

You can easily check whether the solution is correct. The matrix product A times X should equal the right hand side b. Does it? Check it out.

If you have MATLAB's Symbolic Math Toolkit, you can also use the "solve" command to solve the above system. Enter syms x y z eq1 = 'x - 2*y + z = 0'; eq2 = '2*y - 8*z = 8'; eq3 = '-4*x + 5*y + 9*z = -9'; [x,y,z] = solve(eq1, eq2, eq3)

When you have a system with fewer equations than unknowns, you can find the symbolic solution for some of the variables in terms of others, which we could call "free" variables. Consider the following system of three equations in four unknowns. x – 2y + z + 2w = 0 2y – 8z + w = 8 -4x + 5y + 9z - w = -9

Page 44: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 44

We can solve for x, y, and z in terms of w. The last entry in the "solve" command tells

which variables are to be solved for, and hence which variable will be free. Enter

syms x y z w

eq1 = 'x - 2*y + z + 2* w = 0';

eq2 = '2*y - 8*z + w = 8';

eq3 = '-4*x + 5*y + 9*z - w = -9';

[x,y,z] = solve(eq1, eq2, eq3, 'x,y,z')

The seidel.m function

Syntax seidel(A,b,x0,tol,itmax) To finds the solution of a linear system using Gauss-Seidel method

INPUTS: A: nxn matrix

b: nx1 coefficient vector

x0: an initial vector, must be column

tol: a tolerance

itmax: maximum number of iterations

Example Use MATLAB function seidel.m to findthe solution of the following linear system with initial guess 0, 1, 0. 4x1 + x2 + 2 x3 = 1 2x1 +5 x2 + x3 = 14 3x +2x +6 x =9

NORM – Vector Norm

norm - Vector and matrix norms

Syntax >>n=norm(A) >>n = norm(A,p)

Description

The norm of a matrix is a scalar that gives some measure of the magnitude

of the elements of the matrix. The norm function calculates several different

types of matrix norms:

n = norm(A) returns the largest singular value of A, max(svd(A)).

n = norm(A,p) returns a different kind of norm, depending on the value of p.

Page 45: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 45

Example1:

x = [0 1 2 3] x = 0 1 2 3 sqrt(0+1+4+9) % Euclidean length ans = 3.7417 norm(x) ans = 3.7417 n = length(x) % Number of elements n = 4 rms = 3.7417/2 % rms = norm(x)/sqrt(n) rms = 1.8708

Example2:

Let x0 = [0.95 1.02 0.89] and x1 = [1.00 0.99 0.95] Find the error for this iteration

LU Factorization

lu - LU matrix factorization

Syntax

>>Y = lu(A) >>[L,U] = lu(A) >>[L,U,P] = lu(A)

Description

returns unit lower triangular matrix L, uppertriangular matrix U, and permutation matrix P so that P*A = L*U INPUTS: A: nxn matrix

Page 46: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 46

Example1: Let A = [ 1 2 3 4 5 6 7 8 0 ]; To see the LU factorization, call lu with two output arguments. >>[L1,U] = lu(A) L1 = 0.1429 1.0000 0 0.5714 0.5000 1.0000 1.0000 0 0 U = 7.0000 8.0000 0 0 0.8571 3.0000 0 0 4.5000 Using three arguments on the left side to get the permutation matrix as well, >>[L2,U,P] = lu(A) returns a truly lower triangular L2, the same value of U, and the permutation matrix P. L2 = 1.0000 0 0 0.1429 1.0000 0 0.5714 0.5000 1.0000 U = 7.0000 8.0000 0 0 0.8571 3.0000 0 0 4.5000 P = 0 0 1 1 0 0 0 1 0 Note that L2 = P*L1.

Page 47: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 47

4. Laboratory Problem Description

In this laboratory you are required to Find the solution of the following systems of

linear equation:

1) x1 + x2 + x3 = 3

4x1 - x2 - x3= 2

x1 + 2x2 - x3= 2

2)

Given the following system

4x1+3x2+7x3= 3 3x1+2x2+1x3= 1 2x1+3x2+4x3= 2

Using MATLAB commands solve the following system using Gaussian elimination with partial pivoting.

Find P, L, and U.

Solve the system using Gauss-Seidal method in MATLAB. Consider the

initial points x= [0 0.2 0.3] and to be 0.01.

5. Laboratory Exercises

EX1: Use Left Division methods to solve the following system

x + 4y + 3z = 10 2x + y – z = -1 3x – y – 4z = 11

EX2: Given the following system of linear equation 5 x1 + x2 + x3 +2x4 = 8 2 x1 +4 x2 – x4 = -3 x1 + 3x3 = 7 2 x1 – x2 +3 x3 +8x4 = 17

1. Find the L,U and P factorization 2. Find the solution of the system using

a. Left division b. Gauss-Seidel method with ε = 0.001 and initial guess = [0,0,0,0]t c. Gauss-Seidel method with ε =10-6 and initial guess=[0.5,-0.2,1,0.2]t

Page 48: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 48

Laboratory #6 – Polynomials

1. Laboratory Objective

The objective of this introductory laboratory is to introduce Polynomials in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Know how to represent polynomials in MATLAB b. Compute the roots for a given polynomial c. Evaluate polynomial d. Compute polynomial derivative

3. Laboratory Introductory Concepts In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:

To enter this into MATLAB, just enter it as a vector in the following manner

>>x = [1 3 -15 -2 9] x = 1 3 -15 -2 9

MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,

would be represented in MATLAB as: y = [1 0 0 0 1]

You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such as

Page 49: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 49

Finding the roots would be as easy as entering the following command; roots([1 3 -15 -2 9]) ans = -5.5745 2.5836 -0.7951 0.7860

Polynomial with specified roots

Syntax >>p = poly(A) >>p = poly(r)

Description p = poly(A) where A is an n-by-n matrix returns an n+1 element row vector whose

elements are the coefficients of the characteristic polynomial, . The coefficients are ordered in descending powers: if a vector c has n+1 components,

the polynomial it represents is p = poly(r) where r is a vector returns a row vector whose elements are the coefficients of the polynomial whose roots are the elements of r.

Remarks Note the relationship of this command to

r = roots(p) which returns a column vector whose elements are the roots of the polynomial specified by the coefficients row vector p. For vectors, roots and poly are inverse functions of each other, up to ordering, scaling, and roundoff error.

Example1 MATLAB displays polynomials as row vectors containing the coefficients ordered by descending powers. The characteristic equation of the matrix

A = 1 2 3 4 5 6 7 8 0

is returned in a row vector by poly: p = poly(A) p = 1 -6 -72 -27

Page 50: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 50

The roots of this polynomial are returned in a column vector by roots: r = roots(p) r = 12.1229 -5.7345 -0.3884

Polynomial derivative

polyder - Polynomial derivative

Syntax

k = polyder(p) k = polyder(a,b) [q,d] = polyder(b,a)

Description

The polyder function calculates the derivative of polynomials, polynomial

products, and polynomial quotients. The operands a, b, and p are vectors

whose elements are the coefficients of a polynomial in descending powers.

k = polyder(p) returns the derivative of the polynomial p.

k = polyder(a,b) returns the derivative of the product of the polynomials a and

b.

[q,d] = polyder(b,a) returns the numerator q and denominator d of the

derivative of the polynomial quotient b/a.

Example1

The derivative of the product is obtained with

>>a = [3 6 9];

>>b = [1 2 0];

>>k = polyder(a,b)

k =

12 36 42 18

This result represents the polynomial

Page 51: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 51

Polynomial Evaluation

Syntax >>y = polyval(p,x) Description y = polyval(p,x) returns the value of a polynomial of degree n evaluated at x. The input argument p is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial to be evaluated.

x can be a matrix or a vector. In either case, polyval evaluates p at each element of x. . Examples

The polynomial is evaluated at = 5, 7, and 9 with >>p = [3 2 1]; >>polyval(p,[5 7 9]) ans = 86 162 262

Page 52: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 52

4. Laboratory Problem Description

In this laboratory you are required to find the value of the following polynomials:

at s=2,

y = x4 + 2 x

3 – 7 x

2 – 8 x + 12

Compute the derivative for the following polynomials:

f(x)=

12)( 3 xxxf

5. Laboratory Exercises

EX1: Find the value of the following polynomials:

f(x) = cos(x)+sin(3+x) for x=90, 270

xxxf 2)( 2 for x=4, 0.5

EX2: Compute the deravative for the following polynimials

f(x) = e3x

+2

2)( xxf

Page 53: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 53

Laboratory #7 – Eigenvalues and Eigenvectors

1. Laboratory Objective

The objective of this introductory laboratory is to introduce eigenvalues in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Construct characteristics equation b. Compute eigenvalues and eigenvectors.

3. Laboratory Introductory Concepts

Eigenvalues and eigenvectors

Syntax

d = eig(A) d = eig(A,B) [V,D] = eig(A)

Description

d = eig(A) returns a vector of the eigenvalues of matrix A. d = eig(A,B) returns a vector containing the generalized eigenvalues, if A and B are square matrices. [V,D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V) of matrix A, so that A*V = V*D. Matrix D is the canonical form of A — a diagonal matrix with A's eigenvalues on the main diagonal. Matrix V is the modal matrix — its columns are the eigenvectors of A.

Characteristic Equation

The characteristic equation is the equation which is solved to find a matrix's

eigenvalues, also called the characteristic polynomial. For a general matrix ,

the characteristic equation in variable is defined by

(1)

Page 54: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 54

where is the identity matrix and is the determinant of the matrix . Writing

out explicitly gives

(2)

so the characteristic equation is given by

(3)

The solutions of the characteristic equation are called eigenvalues, and are extremely important in the analysis of many problems in mathematics and physics. The polynomial left-hand side of the characteristic equation is known as the characteristic polynomial.

Example

Compute characteristic polynomial for :

>> A=[10 -7 0;-3 2 6;5 -1 5] A = 10 -7 0 -3 2 6 5 -1 5 >> p = poly(A) p = 1.0000 -17.0000 65.0000 155.0000

Page 55: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 55

4. Laboratory Problem Description

In this laboratory you are required to find eigenvalue and eigenvectors for A in the

following systems of linear equation Ax=B:

17x1+2x2+3x3+4x4 = 4

5x1+6x2+7x3+8x4 = 3

9x1+10x2+11x3+12x4 = 2

13x1+14x2+15x3+16x4 = 1

Apply the following commands : >> A = [ 1 2 ; 2 1 ] >>[X D] = eig(A); Verify that the columns of X in the example above indeed are eigenvectors to the matrix A. In other words, multiply (using Matlab) the matrix A to the columns (one at a time) of X and check that they are eigenvectors corresponding to the eigenvalues.

Compute characteristic polynomial for :

A=[2 3 1;-1 2 3;0 1 2]

5. Laboratory Exercises

EX1: Given the following matrix:

321

301

023

A

Using MATLAB commands find the following:

The eigenvalues of matrix A

The eigenvectors of matrix A

EX2: Find the characteristic polynomial for A in EX1

Page 56: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 56

Laboratory #8 – Interpolation

1. Laboratory Objective

The objective of this introductory laboratory is to introduce interpolation polynomial.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Finding the coefficients of the Lagrange interpolating polynomial b. Finding interpolating polynomial using MATLAB

3. Laboratory Introductory Concepts Polynomial curve fitting Syntax

>>p = polyfit(x,y,n) Description

p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits the data, p(x(i)) to y(i), in a least squares sense. The result p is a row vector of length n+1 containing the polynomial coefficients in descending powers:

[p,S] = polyfit(x,y,n) returns the polynomial coefficients p and a structure S for use with polyval to obtain error estimates or predictions.

Example:

Given x

xf1

)( find the interpolating polynomial approximate the value of 1.5

x 2 4 5

f(x) 0.5 0.25 0.2

>> x=[2 4 5] x = 2 4 5 >> y=[0.5 0.25 0.2] y = 0.5000 0.2500 0.2000

Page 57: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 57

>> p=polyfit(x,y,2) p = 0.0250 -0.2750 0.9500 >> polyval(p,1.5) ans = 0.5937

The lagrange Function

Syntax

>>lagrange(x,y,a)

Description determines the coefficients of the Lagrange interpolating polynomial p(x) and computes p(a) INPUTS: The vectors x and y and the value a

Example:

Use lagrange.m function to find the Lagrange interpolating polynomial and approximate the value of 1.5

x 0 1 2 3

y -5 -6 -1 16

>>x=[0 1 2 3]

>>y=[-5 -6 -1 16]

>>lagrange(x,y,1.5)

4. Laboratory Problem Description

In this laboratory you are required to find the interpolating polynomial of the following data.

z 1 2 3 4 4.5

w -1 0 3 3.5 2

And approximate the value of f(2. 5).

Page 58: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 58

5. Laboratory Exercises

EX1: Find the coefficients of the Lagrange interpolating polynomial that interpolates

the function 2)( xxf at 25 equally spaced points in the interval [4,7].

Approximate the value of f(5.975) EX2: Find the interpolating polynomial that interpolates the function f(x) = sin(3+x) over the interval [0,π] using 5 equally spaces.

Approximate the values of )3

(

f and )2

(

f

Page 59: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 59

Laboratory #9 – Least Squares Regression

1. Laboratory Objective

The objective of this introductory laboratory is to introduce least square regression in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to: a. Finding the linear least square using MATLAB b. The linearization using MATLAB c. The second-order approximating polynomial (nonlinear regression) using MATLAB

3. Laboratory Introductory Concepts Least Square Function

Syntax >> linlsqr(x,y)

Description

Constructs a least square line y = ax + b that best fits a table of x and y values INPUTS: The ROW vectors x and y

MATLAB Code function linlsqr(x,y) % Construct a least square line y=ax+b % that fits x and y row or column vectors. n=length(x); n=length(y); sumx=sum(x); sumy=sum(y); sumx2=sum(x.*x); sumxy=sum(x.*y); a=(n*sumxy-sumx*sumy)/(n*sumx2-sumx^2); b=(sumx2*sumy-sumxy*sumx)/(n*sumx2-sumx^2); disp(' linear least squares') fprintf('\n a =%12.6f\n',a) fprintf(' b =%12.6f\n',b) disp('_________________________________________________________') disp(' x y a*x+b |y-(ax+b)| ') disp('_________________________________________________________') for i=1:n yl=a*x(i)+b; err(i)=abs(yl-y(i)); fprintf('%6.2f %6.2f %12.6f %12.6f\n',x(i),y(i),yl,err(i)) end err=sum(err.*err); fprintf('\n E(a,b) =%12.6f\n',sum(err))

Page 60: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 60

Example:

Constructs a least square line y = ax + b, that best fits the following values of x and y

x 2 4 5

y 0.5 0.25 0.2

>> x=[2 4 5] x = 2 4 5 >> y=[0.5 0.25 0.2] >> y y = 0.5000 0.2500 0.2000 >> linlsqr(x,y) linear least squares a = -0.103571 b = 0.696429 _________________________________________________________ x y a*x+b |y-(ax+b)| _________________________________________________________ 2.00 0.50 0.489286 0.010714 4.00 0.25 0.282143 0.032143 5.00 0.20 0.178571 0.021429 E(a,b) = 0.001607

Example: Find the least square polynomial of degree 2

x 0 -1 4 5 7

y 5 1 3 2 -1

>>x=[0 -1 4 5 7]

>>y=[5 1 3 2 -1]

>>polyfit(x,y,2)

Page 61: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 61

linear regression

The data are pairs of independent and dependent variables {(xi,yi): i=1,...,n}. The fitted equation is written G(x) = a1 + a2 x where G is the predicted value of the response obtained by using the equation.

a1 and a2 given by:

22

2

1)( xxN

xfxxfa

222)( xxN

fxxfNa

linearization line

The goal of linearization is to approximate a curve with a line.The basic idea of linearization is to find the equation of the tangent line at a certain point, and use the tangent line to estimate the desired value of the original function.

Syntax G(x) = a1 xa2 , where

22

2

1

)( xxN

fxxxfa

222

)(a

xxN

fxfxN

1

1

aea

Page 62: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 62

4. Laboratory Problem Description

In this laboratory you are required to find the least square polynomial of degree 3

x 1 3 4 5 7

y 0 1 3 2 -1

>>x=[1 3 4 5 7]

>>y=[0 1 3 2 -1]

>>polyfit(x,y,3)

Write a MATLAB script to find the least square line that best fits the following data, Apply linear regression, linearization, and nonlinear regression

x 5 7 6 4

y 8 9 4 1

using the formulas

22

2

1)( xxN

xfxxfa

222)( xxN

fxxfNa

(Hint: G(x) = a1 + a2 x)

Linear Regression Solution:

x=[5 7 6 4] y=[8 9 4 1] disp=('linear regression') N=length(x) sumx=sum(x) sumy=sum(y) sumxy=sum(x.*y) sumsqx=sum(x.^2) a1=((sumy*sumsqx)-(sumx*sumxy))/(N*sumsqx-(sumx)^2) a2=(N*sumxy-sumx*sumy)/(N*sumsqx-(sumx)^2) G=a1+a2*x

Page 63: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 63

Linearization Solution:

disp=('linearization') xbar=log(x) ybar=log(y) sumybar=sum(ybar) sumsqxbar=sum(xbar.^2) sumxbar=sum(xbar) sumxybar=sum(xbar.*ybar) sqsumxbar=sum(xbar.^2) a1bar=((sumybar*sumsqxbar)-(sumxbar*sumxybar))/(N*sumsqxbar-

(sumxbar).^2) a1=exp(a1bar) a2=(N*sumxybar-sumxbar*sumybar')/(N*sumsqxbar-(sumxbar).^2) G=a1*x.^a2;

Nonlinear Solution:

disp=('nonlinear') sumysqx=sum(y.*x.^2) sumcueb=sum(x.^3) sumfth=sum(x.^4) A=[N sumx sumsqx; sumx sumsqx sumcueb; sumsqx sumcueb sumfth] B=[sumy ; sumxy ; sumysqx] Sol=A\B a1=Sol(1) a2=Sol(2) a3=Sol(3) G=a1+a2*x+a3*x.^2

Page 64: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 64

5. Laboratory Exercises

EX1: Write a MATLAB script to find the least square line that best fits the following data:

x 0 2 4 6 8 10 12 14 16

y -3.5 1.5 6 13 19.6 26.1 30.3 29.7 31.4

using the formulas

22

2

1)( xxN

xfxxfa

222)( xxN

fxxfNa

22

2

1

)( xxN

fxxxfa

222)( xxN

fxfxNa

1

1

aea

EX2: Apply linearization, and nonlinear regression techniques for EX1

EX3: Find linearization line that best fits the following data

x 2 4 6 8 10 12 14 16

y 2 5 9 18 24 32 40 51

Page 65: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 65

Laboratory #10 – Root Finding Methods

1. Laboratory Objective

The objective of this introductory laboratory is to introduce some of root finding methods build in MATLAB.

2. Laboratory Learning Outcomes: After conducting this laboratory students will be able to:

a. Use inline command. b. Identify the components of:

Bisection Method

Newton Method

Secant Method c. Calculate roots of the equation using Bisect.m , Secant.m and Newton.m d. Apply speed command (tic, toc).

3. Laboratory Introductory Concepts

Construct inline object

Syntax >> inline(expr)

Description

inline(expr) constructs an inline function object from the MATLAB expression contained in the string expr.

Example:

>> g = inline('t^2')

g=

Inline function:

g(t) = t^2

Stopwatch timer Syntax

>> tic >> ….. % any statments >>toc

Page 66: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 66

Description tic starts a stopwatch timer.toc prints the elapsed time since tic was used.t = toc returns the elapsed time in t.

Example:

>> tic >> for n = 1:10 A = rand(n,n); >> toc Elapsed time is 58.451261 seconds.

The bisect.m function Syntax

>>bisect(f,a,b,tol,n) Description

Finds the solution of an equation using bisection method INPUTS: f: the f(x) function a and b: endpoints tol: a tolerance n: The maximum number of iterations

Example Use MATLAB function bisect.m to find the roots of the function f(x) = x3-x2-1 in [1,2] where ε = 0.01

>> f= inline('x^3-x^2-1')

f = Inline function: f(x) = x^3-x^2-1 >> bisect(f,1,2,0.01,15) _____________________________________________________ iter a b c f(c) |b-a|/2 _____________________________________________________ 0 1.0000 2.0000 1.500000 0.125000 0.500000 1 1.0000 1.5000 1.250000 -0.609375 0.250000 2 1.2500 1.5000 1.375000 -0.291016 0.125000 3 1.3750 1.5000 1.437500 -0.095947 0.062500 4 1.4375 1.5000 1.468750 0.011200 0.031250

Page 67: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 67

5 1.4375 1.4688 1.453125 -0.043194 0.015625 The secant.m function Syntax

>> secant(f,x0,x1,tol,n)

Description Finds the solution of an equation using the secant method INPUTS: f: the f(x) function x0 and x1: initials approximations tol: a tolerance n: The maximum number of iterations

Example

Find the root of f(x)=x6-x-1 in [1,1.5], ε =0.05 using secant.m >> f= inline('x^6-x-1') f = Inline function: f(x) = x^6-x-1 >> secant(f,1,1.5,0.05,15) ______________________________________________________________ iter xn f(xn) f(xn+1)-f(xn) |xn+1-xn| ______________________________________________________________ 0 1.000000 -1.000000 0 1.500000 8.890625 9.890625 0.500000 1 1.050553 -0.706218 -9.596843 0.449447 2 1.083627 -0.464507 0.241711 0.033074

The newton.m function Syntax

>>newton(f,df,x0,tol,n)

Description Finds the solution of an equation using the Newton method INPUTS: f: the f(x) function df: the f '(x) function x0: initials approximation tol: a tolerance n: The maximum number of iterations

Page 68: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 68

Example

Find the root of f(x)=x6-x-1 , ε =0.05 using newton.m

>> f= inline('x^6-x-1') f = Inline function: f(x) = x^6-x-1 >> df=inline('6*x^5-1') df = Inline function: df(x) = 6*x^5-1 >> newton(f,df,0.5,0.05,15) ______________________________________________ iter x f(x) df(x) |xn+1-xn| ______________________________________________ 0 0.500000 -1.484375 -0.812500 1 -1.326923 5.785438 -25.681979 1.826923 2 -1.101651 1.889224 -10.735786 0.225272 3 -0.925676 0.554828 -5.078000 0.175974 4 -0.816415 0.112535 -3.176241 0.109261 5 -0.780985 0.007897 -2.743272 0.035430

4. Laboratory Problem Description

In this laboratory you are required to find the roots of the following equations �f(x) = -2x4 +x2 +12 �f(x) = sin(x) �f(x) = 3x3 –x2 +4 �f(x) = x2 - cos (x)

Using Bisection,Secant and Newton methods in [1,2] where ε =0.05

5. Laboratory Exercises

EX1: Use MATLAB build-in function to compare the speeds between (bisection,

newton and secant methods) for the following functions:

1-f(x) = e3x

+2 in [0,2]

2- 2)( xxf in [0,1]

Page 69: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 69

Appendix A: Rules to fallow by Computer Lab Users The loud conversations / discussion that disturbing the other users is prohibited.

Audio CDs or applications with audio output may only be used with headphones with minimum

volume that it should not be disturb other users.

All cell phones are to be turned off or set to silent while in the lab. If you receive a phone call, you

should exit the lab before answering your cell phone.

Do not bring food or beverages inside the lab.

Any file saved on the computer hard drive will be deleted without notice. Students should save their

work onto an external storage device such as USB drive or CD.

Changing hardware and software configurations in the computer labs is prohibited. This includes

modifications of the settings, modification of system software, unplugging equipment, etc.

Open labs are reserved for academic use only. Use of lab computers for other purposes, such as

personal email, non-academic printing, instant messaging, playing games, and listening to music is not

permitted.

Please leave the computer bench ready for the next patron. Leave the monitor on the login screen, and

do not forget to take goods related to you. While leaving computer bench please push the chair inside

the computer bench.

Users are responsible for their own personal belongings and equipment. Do not leave anything in the

Computer Lab unattended for any length of time. The Computer Labs staffs are not responsible for lost

or stolen items.

Users are not allowed to clear paper jams in the printer by themselves.

Operate the lab equipments with care.

After using white-board the user must clean for other user.

Thanks for your cooperation.

Information Science Department

Page 70: Lab Manual - Ku Manuals/ISC 210 Lab-Manual.pdf · Lab Manual ISC 210 Computational Methods ... Rules to fallow by Computer Lab Users ... Cheating in Lab Work or Lab Project will result

ISC 210 Computational Methods P a g e | 70

Appendix B: Endorsement

LABORARTORY MANUAL FOR

ISC 210 Computational Methods

# Instructor name Remarks Signature Date

1 Dr. Jehad Al Dallal

2 Latifa Al-Dhaferi