Computational Method Lab
Computational Method Lab
3
Main Characteristics of Matlab.
1. Operators and Special Characters.
2. Specialized Math Functions.
3. Matrix Functions.
4. Powerful Tools for 2-D and 3-D graphs.
5. Matrices and Linear Algebra.
6. Interpolation and Polynomials.
7. General Purpose Commands.
8. Elementary Matrices and Matrix
Manipulation.
4
1. Operators and Special Characters.
Just like a calculator, Matlab can do simple math. That is the most typical used
that the beginners make of the Matlab. The main Matlab arithmetic operators
are shown in the table below.
5
variable-naming rules
1. Variables names are case sensitive (total, Total, toTal are all different variables).
2. Variables names can contain up to 31 characters.
3. Variables names must start with a letter, followed by any number of letters, digits, or underscores.
Punctuation characters are not allowed, since many of them have special meaning to Matlab.
Eg
6
variable-naming rules continued….
4. There’re a special variables and constants that should not be used in the
programming with Matlab. Such as:
7
Math lab commands
• cd Change to another directory
• pwd Display (print) current working directory
• dir Display contents of current working directory
• what Display matlab-relevant files in current working directory
• Exit stop math lab session
8
The commands to managing the workspace are:
9
clear commands
• The group of clear commands and their descriptions that you can find in
Matlab are:
• CLEAR: Clear variables and functions from workspace.
• CLEAR GLOBAL: removes all global variables. CLEAR FUNCTIONS removes all
compiled M- and MEX-functions.
• The command “clear all” removes all variables, global variables, functions
and MEX links, it’s command prompt also removes the Java packages
import list
10
Managing commands and functions.
11
FORMAT Set output format
13
1st. method: with Matlab help (Number system conversion )
• dec2bin(integer)
• base2dec(‘binary no',2)
• base2dec(‘octal no',8)
• base2dec(‘hexa decimal',16)
• dec2hex(integer)
• hex2dec(‘hexa decimal’)
• base2dec('string', base)
• bin_str = dec2bin(base2dec(‘oct_str’, 8))… from octal to binary
14
Bisection Method for root finding
15
Bisection Method for root finding
• clc • fprintf('%d)\txl%d=%f\txu%d=%f\txm%d=%f\
tea%d=%f\tet%d=%f\n',i,i,xl,i,xu,i,xm,i,ea,i,et)
• clear all
• if(f(xm)*f(xl)<0)
• f=inline(input('Enter the equation : ','s'))
• xl=xl;
• xl=input('Enter the lower bound Xl = : ');
• xu=xm;
• xu=input('Enter the uppper bound Xu = : ');
• else
• n= input('Enter the nu of iteration n = : ');
• xl=xm;
• if(f(xl)*f(xu)<0)
• xu=xu;
• xm=0;
• end
• for i=1:n
•
• end
pre=xm;
• xm=(xl+xu)/2; • root=xm
• cur=xm; • else
• ea= abs(((cur-pre)*100)/cur); • disp('The root is not found b|n', xl, ' and ',xm)
• et= abs(1-xm)*100; • end
16
False position Method for root finding
17
False position Method for root finding
• clc • fprintf('%d)\txl%d=%f\txu%d=%f\txm%d=%f\
• clear all tea%d=%f\tet%d=%f\n',i,i,xl,i,xu,i,xm,i,ea,i,et)
• f=inline(input('Enter the equation : ','s')) • if(f(xm)*f(xl)<0)
• xl=input('Enter the lower bound Xl = : '); • xl=xl;
• xu=input('Enter the uppper bound Xu = : '); • xu=xm;
• n= input('Enter the nu of iteration n = : '); • else
• if(f(xl)*f(xu)<0) • xl=xm;
• xm=0; • xu=xu;
• for i=1:n • end
• pre=xm; • end
• xm=(xu*f(xl)-xl*f(xu))/(f(xl)-f(xu)); • root=xm
• cur=xm; • else
• ea= abs(((cur-pre)*100)/cur);
• disp('The root is not found b|n', xl, ' and ',xm)
• et= abs(1-xm)*100;
• end 18
functions
20
Logical operator
21
If command
22
If-elseif-else command
23
for command
24
while command
25
Fixed point iteration method for root finding
• function [x,err,xx] = fixpt(g,x0,TolX,MaxIter)
• if nargin < 4, MaxIter = 100; end
• if nargin < 3, TolX = 1e-6; end
• xx(1) = x0;
• for k = 2:MaxIter
• xx(k) = feval(g,xx(k - 1)); %Eq.(4.1.3)
• err = abs(xx(k) - xx(k - 1));
• if err < TolX, break; end
• end
• x = xx(k);
• if k == MaxIter fprintf('Do not rely on me, though best in %d iterations\n',MaxIter)
• end 26
Newton Raphson method for root finding
• % newtraph: Newton-Raphson root location zeroes
• % [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,p1,p2,...): uses Newton-
Raphson method to find the root of func
• % input: % f = name of function % df = name of derivative of function
• % xr = initial guess % es = desired relative error (default = 0.0001%)
• % maxit = maximum allowable iterations (default = 50)
• % p1,p2,... = additional parameters used by function % output:
• % root = real root % ea = approximate relative error (%)
• % iter = number of iterations
• % break: Terminate execution of WHILE or FOR loop.
27
Newton Raphson method for root finding
• function [root,ea,iter]=newtraph(f,df,xr,es,maxit,varargin)
• if nargin<3,error('at least 3 input arguments required'),end
• if nargin<4|isempty(es),es=0.0001;end
• if nargin<5|isempty(maxit),maxit=50;end
• iter = 0;
• while (1)
• xrold = xr;
• xr = xr - f(xr)/df(xr);
• iter = iter + 1;
• if xr ~= 0, ea = abs((xr - xrold)/xr) * 100; end
• if ea <= es | iter >= maxit, break, end
• end
• root = xr; 28
Roots of polynomials.
• The roots of polynomials are the values for which the polynomial is zero, to finding
the zeros of the polynomials is a problem common to many disciplines. Matlab can
solve this kind of problems and also provides other polynomials manipulations
tools as well.
• How you can enter polynomials to Matlab?
• In Matlab a polynomials is represented by a row vector of its coefficients in
descending order, for example, the polynomial f(x) = x4 –12x3 + 25x2 + 12x + 16 is
entered as:
• >> p1 = [1 –12 25 12 16]; ⇒ f(x) = x4 –12x3 + 25x2 + 12x + 16
• Given this form the roots of the polynomial are found by using the function “roots”
• >> r = roots (p1) ⇒ Is the same to type: roots ([1 –12 25 12 16]) r
= 9.0797 3.4977
- 0.2887 + 0.6484i - 0.2887 - 0.6484i 29
• Polynomial multiplication is supported by the function “conv” which perform the
convolution of two arrays. In the preceding case we have:
>> x1= [2 1]; x2 = [1 3 6]; >> prod = conv(x1,x2)
prod = 2 7 15 6 ⇒ 2x3 + 7x2 + 15x + 6
• Multiplication of more than two polynomials requires repeated used of -conv-
command.
• In some special cases it necessary to divide one polynomial into another, this is
accomplished with the function “deconv”
>> [div,rem]= deconv (x1,x2)
• Because the differentiation of a polynomials is simple to express, Matlab offers to you
the function “polyder” for polynomial differentiation, suppose that
f(x) = 4x5 +3x4 +2x3 +x2 + 1 ,then the first derivate functions of f(x) is
f ′(x) = 20x4 + 12x3 + 6x2 + 2x
>> p = [4 3 2 1 0 1]; de_p = polyder (p)
der_p = 20 12 6 2 0 30
Matrix and vectors
• Arrays: are lists of numbers or expressions arranged in horizontal rows and
vertical columns.
• single row, or single column array is called a Vector
• An array with m rows and n columns is called a matrix of size m×n
Array Construction
1. Using the colon notation: x:y means roughly “generate the ordered set of
numbers from x to y with increment 1 between them.” The syntax x:d:y
means roughly “generate the ordered set of numbers from x to y with
increment d between them.”
2. Function linspace(start,stop,npoints): generate a vector of evenly spaced
points between two end points. Linspace(start, stop) will generate a vector
of 100 points.
31
Row vector can create with space ( like, R=[n1 n2 n3 … n]) eg. R1=[ 1 2 3 4 ] or
comma ( like, R=[n1,n2,n3,…,n]) eg. R2=[1,2,3,4]
• Row vector can create with semicolon (eg. C=[1;2;3;4] or writing down a=[1
2]
• some important points to be noted are:
Square brackets are used to denote a vector or matrix.
Spaces or commas are used to denote columns.
The semicolon operator or newline character is used to separate rows.
The single quotation mark (‘) transposes arrays.
• The dot operator signifies an element-by-element operation. The dot operator
is defined for multiplication (.*), division (./), and exponentiation (.∧), but not
for addition and subtraction. 2.*A is similar to 2*A
32
To type a matrix into matlab you must
begin with a square bracket[
separate elements in a row with commas or spaces
use a semicolon ; to separate rows
end the matrix with another square bracket].
Useful Matrix Generators
1. zeros a matrix filled with zeros. Zeros(2,3)
2. ones a matrix filled with ones. Eg. Ones(2,3)
3. “magic” function create a magic square constructed from the integers 1 through N^2 with
equal row, column, and diagonal sums,
4. rand a matrix with uniformly distributed random elements eg. rand(2,2)
5. randn a matrix with normally distributed random elements eg. randn(2,2)
6. eye identity matrix eg eye(3)
7. D=diag([1 2 3]) create a matrix whose diagonal is 1 2 3
8. A = pascal(3) create symmetric matrix 33
Accessing sub matrix
• J(2,3) % 2nd row 3rd column
• J(:,3) % 3rd column
• J(:,2:3) % columns 2 to 3
• J(4,:) % 4th row
• J(:) % all row and column
• J(2:3,2:3) % rows 2 to 3 & cols 2 to 3
• J(2:3,1:3) % 2nd to 3rd row from column 1 to 3
34
Built-in Functions in matrix
• size(A)
• Length(A)
• diag(A) extracts its diagonal entries
• triu(A):Extract upper diagonal
• tril(A): Extract lower diagonal
• trace(A) performs the sum of the diagonal elements of matrix A,
• spy(A) will produce a graphical display of the location of the nonzero entries in
A (it will also give a value for nz-the number of nonzero entries):Eg spy(A), grid
• det(A) calculate the determinant of A
• inv(A) calculate the inverse of A
• rank(A) calculate the rank of A
• Find(A) indices of nonzero entries 35
Functions in matrix
• max(A): Maximum elements of a matrix
• min(A): Minimum elements of a matrix
• numel(A): Number of elements in array or subscripted array
• sort(A): Sort array elements in ascending or descending order
• sum(A): Sum of matrix elements
• mean(A): The average of the elements for matrix
• A+D: Adding two matrices
• A*D: multiplying two matrix
• A.*D: element by element multiplication
• A.^2: power element by 2
• A^2: Power matrix A by number
36
Norms
For matrices:
• norm (x) is the largest singular value of x, max(svd(x)).
• norm (x,2) is the same as norm (x).
• norm (x ,1) is the 1-norm of x, the largest column sum, = max(sum(abs(x))).
• norm (x,inf) is the infinity norm of x, the largest row sum, = max(sum(abs(x'))).
• norm (x,'fro') is the Frobenius norm, sqrt(sum(diag(x'*x))).
• norm (x,P) is available for matrix x only if P is 1, 2, inf or 'fro'.
For vectors:
• norm (V,P) = sum(abs(V).^P)^(1/P).
• norm (V) = norm (V,2).
• norm (V,inf) = max(abs(V)).
• norm (V,-inf) = min(abs(V)). 37
Systems of Linear Equations
A general system of linear equations can be expressed in terms of a coefficient
matrix A, a right-hand-side (column) vector b and an unknown (column) vector x
as Ax = b
or, component wise, as
The standard Matlab routine for solving systems of linear equations is invoked by
calling the matrix left-division routine, x = A \ b == A^-1*b == inv(A)*b
38