0% found this document useful (0 votes)
68 views

ME18A - MATLAB Lecture Notes

Uploaded by

Killen B.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

ME18A - MATLAB Lecture Notes

Uploaded by

Killen B.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Lecture 1

To add comments to MATLAB code, use percent (%) symbol - green color

Input - request user input


Syntax:
x = input(prompt)
txt = input(prompt, ‘s’)

x = input(prompt) - displays the text in prompt and waits for the user
to input a value and press return/enter key.

Ex:
prompt = “what is the value?”;
x = input(prompt) % can enter any number
y = x*10

Ex:
width = input (‘Enter the width:’)
len = input (‘Enter the length:’);
% width = 5;
% len = 10.2;
area = len*width; % This computes the area of a rectangle
fprintf(‘The area of the rectangle with length %f and width %f is
%f \n’,len,width,area);

Lecture 2

Round - round to the nearest decimal or integer


Y = round(X) - rounds each element of X to the nearest integer. In the
case of a tie, where an element has a fractional part of 0.5 (within
roundoff error) in decimal, the round function away from zero to the
nearest integer with larger magnitude

Y = round(X,N) - rounds to N digits:


Ex:
y = 11;
x = y/2;
difference = round(x)-x;
difference == 0

difference =
0.5000

Array
A = [ 4 5 3 7 9 11]; % array
B = A; % make copy of A
len = length(A); % how many elements are in A
A1 = A(1:4); % create a new array A1 with the first 4 elements of A
A2 = A(end-3: end); % create a new array A2 with the last 4 elements
of A
A3 = [A1 A2]; % concatenate A1 and A2
A(3) = 13 % replace the third element by 13
x = min(A); % determine the minimum number in the array
[y,i] = max(A); % determine the max number in the array
A(1:3) = [ ]; % Remove the first 3 elements from the array

clc - clears all text from the command window

IMPORTANT FOR QUIZ


Ex:
y = cos(pi*x).*sin(x/2).*tan(x);
X = 0:0.01:2*pi % domain of y, array with the lowest number 0 and
the highest number 2pi in steps of 0.01
M = min(y)
[y,i] = min(y); % where y is the minimum number in y and i is its
location
X(*insert the answer for i*) % gives the x value of the minimum
of y

Ex:
A = 5:2:100; % create an array A with the lowest number 5 and the
highest number 100 in steps of 2
B = 100: -2: 5; % create an array A with the highest number 100
and the lowest number 5 in steps of -2
C = 5: -2: 100; % result will be zero (empty row)
D = 100: 2: 5; % result will be zero (empty row)

Linspace - generate linearly spaced vector


Syntax:
y = linspace(x1, x2) % returns a row vector of 100 evenly spaced
points between x1 & x2
Y = linspace(x1, x2, n) % generates n points. The spacing between
points is (x2-x1)/(n-1)

Ex:
Y = linspace(100, 5, 1000); % 100 to 5 with 1000 values in
between

Lecture 3

Subplot - creates axes in tiled positions


Syntax:
subplot(m,n,p) - divides the figure into an m-by-n grid and
places each plot at position p. The first subplot is the first column
of the first row, the second subplot is the second column of the first
row, etc.

Ex:
subplot(2,1,1);
x=linspace(0,10);
y1=sin(x);
plot(x,y1)

subplot(2,1,2);
y2=sin(5*x);
plot(x,y2)
Ex:
subplot(2,2,1)
x=linspace(0,10);
y1=sin(x);
plot(x,y1)
title(‘Subplot 1: sin(x)’)

subplot(2,2,2)
y2=sin(2*x);
plot(x,y2)
title(‘Subplot 2: sin(2x)’)

subplot(2,2,3)
y3=sin(4*x);
plot(x,y3)
title(‘Subplot 3: sin(4x)’)

subplot(2,2,4)
y4=sin(8*x);
plot(x,y4)
title(‘Subplot 4: sin(8x)’)

Ex:
subplot(2,2,1);
x=linspace(-2,2,50)
y1=x.^2
plot(x,y1)
hold on;

subplot(2,2,2);
y2=sin(x);
plot(x,y2,’--’);
grid on;

3D Plot Ex:
x=1:1:10;
y=x.^2;
z=x+y
plot3(x,y,z)

Ex:
subplot(2,2,1);
x=linspace(-3.8,3.8);
y_cos=cos(x);
plot(x,y_cos);
title(‘Subplot 1: Cosine’)

subplot(2,2,2);
y_poly=1-x.^2/2 + x.^4./24;
plot(x,y_poly,’g’)
title(‘Subplot 2: Polynomial’)

subplot(2,2,[3,4]);
plot(x,y_cos,’b’,x,y_poly,’g’);
title(‘Subplot 3 and 4: Both’)
Diary - Log command window text to file
Diary myDiaryfile %write any code
diary off
*type myDiaryfile* - calls back what was written in the diary
diary off % to close

Taylor - taylor series


Syntax:
T=taylor(f,var)
T=taylor(f,var,a)
T=taylor(_,Name,Value)

T=taylor(f,var)-approximates f w/ the Taylor series expansion of f up


to the 5th order at point var=0. If var is not specified, then taylor
uses the default variable symvar(f,1)

Lecture 4

If, elseif, else - execute statements if condition is true


Syntax:
if expression
statements
elseif expression
statements
else
statements
end

% end evaluates an expression and a group of statements


statements when the expression is true

% an expression is true when its result is nonempty and contains


only nonzero elements (logical/real #s). Otherwise, expression is
false

% elseif and else blocks are optional. The statements execute


only if previous expressions in the if. . .end block are false.

% an if block can include multiple elseif blocks.

For Loop - repeat specified number of times


Syntax:
for index = values
statements
end

Ex (Basic):
for = i=1:5
i % display vector i individually
end

Ex (Basic):
x=-2:2;
for i=1:length(x)
x(i)
end

Ex (Nested for loop):


x=-2:2;
y=1:4;
for i=length(x)
for j=length(y)
A(i,j)=x(i)+y(j) % 5x4 matrix since length(x)=5 (rows) and
length(y)=4 (columns)
end
end

Ex: Loop through the matrix and assign each element a new value.
Assign 2 on the main diagonal, -1 on the adjacent diagonal and 0
everywhere else.

nrows=4;
ncols=6;
A=ones(nrows,ncols)

for c=1:ncols
for r=1:nrows

if r==c
A(r,c)=2;
elseif abs(r-c)==1
A(r,c)=-1;
else
A(r,c)=0;
end

end
end
A

Function - declare function name, inputs, and outputs


Syntax:
Function [y1,...,yN] = myfun(x1,...,xM) - where myfun is the name
of function, x1,...,xM are the inputs, and output to be returned is
y1,...yN
% Valid function names begin w/an alphabetic character, cna contain
letters, numbers or underscores
% Name of file must match name of first function in the file
% In a script file containing commands and function defs, functions
should be at the end of file; script files cannot have same name as a
function file

Function with Multiple Outputs: Define a function in a file named


stat.m that returns the mean and standard deviation of an input
vector:

function [m,s]=stat(x)
n=length(x);
m=sum(x)/n;
s=sqrt(sum((x-m).^2/n));
end

% Call the function from command line:


values=[12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev]=stat(values)
ave=
47.3400
stdev=
29.4124
Multiple Functions in a Function File: Define two functions in a file
named stat2.m where the 1st function calls the 2nd.

function [m,s]=stat2(x)
n=length(x);
m=avg(x,n);
s=sqrt(sum((x-m).^2/n));
end

function m = avg(x,n) % function avg is a local function, only


available to other functions within the same file
m=sum(x)/n;
End

% Call function stat2 from command line:


values=[12.7, 45.4, 98.9, 26.6, 53.1]
[ave,stdev]=stat(values)
ave=
47.3400
stdev=
29.4124

Ex:
inputTemp = input(‘Enter temperature to convert:’);
selection = input(‘Enter 1 to convert to Farenheit and 2 to convert to
Celsius:’)

if selection == 1 % Convert Cel to Fahr


outputTemp = 9/5(inputTemp + 32);
fprintf(‘%.2f degrees C = %.2 degrees F \n’,inputTemp,outputTemp)
elseif selection == 2
outputTemp = 5/9*(inputTemp -32);
fprintf(‘%.2f degrees F = %.2 degrees C
\n’,inputTemp,outputTemp’);
else
fprintf(‘Invalid selection \n’);
end

Ex (Previous ex made easier w/ function command):


inputTemp = input(‘Enter temperature to convert:’);
selection = input(‘Enter 1 to convert to Farenheit and 2 to convert to
Celsius:’)

if selection==1 % Convert Cel to Fahr


outputTemp = convertCeltoFahr(inputTemp);
% outputTemp = 9/5(inputTemp + 32);
fprintf(‘%.2f degrees C = %.2 degrees F
\n’,inputTemp,outputTemp);
elseif selection == 2
% outputTemp = 5/9*(inputTemp-32)
outputTemp=convertFahrtoCel(inputTemp);
fprintf(‘%.2f degrees F = %.2 degrees C
\n’,inputTemp,outputTemp’);
else
fprintf(‘Invalid selection \n’);
end

function outTemp=converceltoFahr(inTemp)
outTemp = 9/5*inTemp + 32;
end

function outTemp=convertFahrtoCel(inTemp)
outTemp=5/9*(inTemp - 32);
end

While Loop - to repeat when condition is true


Syntax:
while expression
Statements
end

Ex:Use a while loop to calculate factorial(10)


n=10; % 10
f=n; % n=9
while n>1
n=n-1; % 9-1=8
f=f*n; % f=90*8
end

% Type in command window:


disp([‘n!=’ num2str(f)]) % displays the value of variable

% Final answer:
n! = 3628800

Ex:
x=[2 43 6 8 1 47 34];
nx=length(x);
acc=0;
counter 1;
while counter <= nx
acc=acc+x*counter; % Add/accumulate
counter=counter+1;
end
Ex:

Lecture 5

Fzero - root of nonlinear function


Syntax:
x=fzero(fun,x0) % tries to find a point x where fun(x)=0. This is
where fun(x) changes sign—fzero cannot find a root of a function like
x^2.
x=fzero(fun,x0,options) % uses options to modify the solution
process
x=fzero(problem) solves a root-finding problem specified by
problem
[x,fval,exitflag,output]=fzero(_)

Ex:
function y = quad1(x)
y=x.^2-3*x+2;
end
% Use fzero to compute the root using an external file
initial_guess=3; % start from 3 and look around 3 until root is found
x1=fzero(@quad1,initial_guess);
% Using anonymous functions
f=@(x) x.^2-3*x+2; %f is the function handle
x2=fzero(f,initial_guess);
f1=@(x) x.^2.*sin(x)-3*x+2;
x3=fzero(f1,0);

x=linspace(-2,2);
plot(x,f1(x));
grid on;

Ex:
fun=@sin; % function
x0=3; % initial point
x=fzero(fun,x0)
x=
3.1416

fun=@cos; % function
x0=[1 2]; % initial interval
x=fzero(fun,x0)
x=
1.5708

Ex: Find a zero of the function f(x)-x^3-2x-5. First write a file


called f.m
function y = f(x)
y=x.^3-2*x-5;
% save f.m on matlab path
% Find the zero of f(x) near 2:

fun=@f; % function
x0=2; % initial point
z=fzero(fun,x0)
z=
2.0946

Roots - polynomial roots


Syntax:
r=roots(p) - returns the roots of the polynomial where p is a
column vector
Ex: Solve the equation 3x^2-2x-4=0.
p=[3 -2 -4]; % 3, -2, and -4 are the corresponding coefficients of
each term
r=roots(p)

Ex: Roots of quartic polynomial. Solve the x^4-1=0


p=[1 0 0 0 -1];
r=roots(p)

Lecture 6

Conv - convolution and polynomial multiplication


Syntax:
w=conv(u,v) - returns the convolution of vectors u and v. If u and v
are vectors of polynomial coefficients, convolving them is the same as
multiplying the two polys.
w=conv(u,v,shape)

Ex: Create vectors u and v containing coefficients of x^2+1 and 2x+7


u=[1 0 1];
v=[2 7]
w=conv(u,v)

Lecture 7 —-> review, skipped


Lecture 8

Taylor Series - lab 2 demonstration

T=taylor(sin(x))
T=X-(X^3)/6 + (x^5)/102
Code:
y=sin(x);
y1=x;
y2=x-(x^3)/factorial(3);
y3=x-(x^3)/factorial(3) + (x^5)/factorial(5)
function er = computeError(estimate, actual)
er=abs((estimate - actual)/actual;
end

To call function:
cy1=computeError(y1, y)*100;
cy2=computeError(y2, y)*100;
cy3=computeError(y3, y)*100;

Logical
Syntax: AND—-> &&
Ex: (x>1) && (x<10)
Syntax: OR —-> ||
Ex: (x>1) || (x<-1)
Inequality A~=B % A is not equal to B

Newton-Raphson Method (for finding roots)


f’(x0)=(0-f(x0))/(x1-x0)
Rearranging
x1=x0-f(x0)/f’(x0)

In general, at step(+), we get x_i+1 = xi - f(xi)/f’(xi)


Ex: f(x)=-0.5+(x/4)+2sinx with an initial guess of 4. Derivative
f’(x)=¼ + 2cosx

1.Iteration: f(x) = 2.0136, f’(x)=2.8646


x1=x0=f(x0)/f’(x0) = 4 - 2.0136/2.8646
= 3.2971
Error= |(3.2971-4)/3.2971)|=0.2132
2. Iteration

ne,~= - determine inequality


Syntax:
A~=B
ne(A,B) % A and B are not equal

AND,&& - Logical AND


Syntax:
expr1 && expr2 - represents a logical AND operation. expr2 is not
evaluated if expr1 is logical 0 (false). Each expression must evaluate
to a scalar logical result.

Ex: (x>1) && (x<10) % logical data types

OR,|| - Logical OR
Syntax:
expr1 || expr2 - represents a logical OR operation. Expr2 is not
evaluated if expr1 is logical 1 (true). Each expression must evaluate
to a scalar logical result

Lecture 9-10

Matrices
A matrix is a rectangular array of numbers enclosed in brackets, which
are the elements of the matrix
● A has two rows and three columns, it’s a 2x3 matrix.
● B has three rows and three columns, it’s a 3x3 matrix.
𝑡ℎ 𝑡ℎ
● A=[A𝑖𝑗 ], where A𝑖𝑗 is the element in the 𝑖 row and the 𝑗 column.

(i.e. 𝐴21= 4 and 𝐵32 = 7)


● The elements 𝐴11, 𝐴22, etc form the main diagonal of the matrix
○ Elements not on the main diagonal are off diagonal elements
● Matrix C is a row vector, matrix D is a column vector
● Square matrix has the same # of rows and columns (i.e. Matrix B
is a square matrix)

● Diagonal matrix is a square matrix w/ zeroes in all off-diagonal


positions. (i.e Matrix D)
● Identity Matrix is a diagonal matrix w/ ones on the main
diagonal. (i.e. 𝐼4 𝑥 4)

● Zero matrix has all elements equal to zero


● Upper triangular matrix has zeros below the main diagonal (i.e.
Matrix U)
● Low triangular matrix has zeros above the main diagonal (i.e.
Matrix L)
● Symmetric matrix is a square matrix symmetric about the main
diagonal
○ The condition for symmetry is 𝑎𝑖𝑗 = 𝑎𝑗𝑖 (i.e. Matrix S)

● Skew-symmetric matrix satisfies 𝑎𝑖𝑗 = -𝑎𝑗𝑖 and implies that all


diagonal elements are zero (i.e. Matrix K)

Matrix Operations
● Equality of matrices: two matrices A and B are equal iff they
have the same elements (i.e. 𝐴𝑖𝑗 = 𝐵𝑖𝑗 for all i and j, basically
copy of each other)
○ For matrices to be equal, they must have the same size
● Transpose: the transpose of matrix A = [𝐴𝑖𝑗 ] is

● Addition of matrices: the sum of two matrices A and B is written


as A+B and has elements 𝐴𝑖𝑗 + 𝐵𝑖𝑗
○ Only matrices of equal sizes can be added
● Scalar multiplication: The produce of a m x n matrix A=[𝐴𝑖𝑗] and a
scalar c is written as cA and is a matrix of size m x n with
elements c𝐴𝑖𝑗

● Matrix multiplication: the product of two matrices 𝐴𝑚 𝑥 𝑛 and 𝐵𝑛 𝑥 𝑝


is a matrix C that has size m x p.
○ Two matrices can only be multiplied if number of column of
the first matrix is equal to the number of rows of the
second matrix

● Minor: For matrix A,the minor 𝑀𝑖 , 𝑗 is the determinant of the

submatrix obtained by deleting the ith row and jth column of A.

● Cofactor: For matrix A, the cofactor 𝐶𝑖 , 𝑗 is given by

𝑀𝑖 , 𝑗 is determinant
Determinants
● A determinant of order n is a scalar associated with a n x n
matrix
1. n=1: matrix A is simply a scalar, the determinant equals the
scalar
2. n=2:

3. n=3:

4. n=4:
Inverse

Dot Product:
Vector on matlab:

Cross Product:
MATLAB Translation
Vector Addition Ex:
function c = myAddVectors(a,b)
% a=[1 2 3]; a=i+2j+3k
% b=[4 5 6]; b=4i+5j+6k
% a+b=
[5 7 9]---->5i+7j+9k
if length(a)==length(b)
c(1)=a(1)+b(1) % call function c
C(2)=a(2)+b(2)
c(3)=a(3)+b(3)
else c=[] % return an empty vector
disp(‘Vector lengths are not equal’)
end

Matrix Addition/Subtraction Ex:


function[status, a]=addMatrices(a1,a2)
[nr1,nc1]=size(a1);
[nr2,nc2]=size(a2); % size gives the # of rows and columns
If (nr1~=nr2||nc1~=nc2)
status=0; % zero means no answer
a=[]; % empty
Return;
end
for i=1:nr1
for j=1:nc1
a(i,j)=a1(i,j)+a2(i,j)
end
status=1; % 1 for valid
end

Dot Product Using For Loop Ex:


function d = myDotProduct(u,v) % uxi + uyj + uzk, vxi +vyj + vzk
len=length(u); % len will give 3 for vector w/ i j k
acc=0;
for i=1:len % repeat 3 times
acc=acc+u(i)*v(i) % where u(i)*v(i) = uxvx + uyvy + uzvz
end
d=acc;
end

Dot Product Using While Loop:


function d = myDotProduct(u,v)
len=length(u);
i=1;
acc=0;
while i<=len
acc=acc+u(i)*v(i)
end
d=acc;
end

Cross Product Ex:

Check Whether Matrices Are Equal Ex:


Function eq = areMatricesEqual(A,B)
[nr,nc]=size(A);
eq=true; % assume it’s true and then check
for i=1:nr
for j=1:nc
if A(i,j)~=B(i,j)
eq=false
break;
end
end
end
end

Minor Ex:
function[status,minor]=computeMinor(A,r,c) % A-matrix, r-row, c-column
[nr,nc]=size(A)
if (r<=0||c<=0||r>nr||c>nc)
status=-1; % -1 for not valid
else
status=1;
A(r,:)=[]; % removes row r regardless of the column number
A(:,c)=[]; % removes column c
minor=det(A) % determinant of A
end
end

Cofactor Ex:
function [status,cofactor]=computeCofactor(A,r,c)
[status,minor]=computeMinor(A,r,c)
cofactor=((-1)^(r+c)).*minor;
end

Determinant Ex:
function [status,a]=computeDeterminant(a1)
[nr,nc]=size(a1);
if nr ~=nc
status=-1;
a=0;
else
a=det(a1);
status=1;
end
end
Matrix Multiplication Ex:
function[status,a]=multiplyMatrices(a1,a2)
[nr1,nc1]=size(a1);
[nr2,nc2]=size(a2);
if nc1~=nr2 % the # of rows and columns of must be the same
status=0;
a=[];
else
a=a1*a2;
status=1;
end

Matrix Transpose Ex:


function[status,a]=transposeMatrix(a1)
a=a1’;
status=1
end

Lab 4 - Newton Raphson Root:


function root=newtonRaphsonMethod(f,df,guess,errTol,maxIter)
curErr=1e^10;
xold=guess;
while curErr>errTol && n<maxIter
xnew=xold-(f(xold)/df(xold));
xold=xnew;
n=n+1;
end
root=xnew;
End

% To call the function:


x=linspace(-2,2);
f=@(x) exp(-x).*sin(2*x)+1 % (e^-x)sin(2x)+1
df=@(x) exp(-x)+(2*cos(2*x))-sin(2*x);
guess=1;
errTol=1e-6;
n=1;
maxIter=1000;
root=newtonRaphsonMethod(f,df,guess,errTol,maxIter);

% Root using built-in function fzero:


r1=fzero(f,-2);

Lab 4 Problem 2:
function[f,Re]=computeFrictionFactor(V,pipe,fluid)
D=pipe(1);
eps=pipe(2);
rho=fluid(1);
mu=fluid(2);
Re=rho*V*D/mu;

if Re<2000
f=64/Re;
elseif Re>4000
g=@(x) 1/sqrt(x)+2*log10(eps/(3.7*D)+2.51/(Re*sqrt(x)));
f=fzero(g,0.1);
else
f=-1;
end
end
Lecture 11-13

Gaussian Elimination & LU Decomposition:


Matlab Ex (Lab 5):
mrdivide, / - solves systems of linear equations xA=B for x
Syntax:
x = B/A
x = mrdivide(B,A)
Matrices A & B must contain the same number of columns; MATLAB®
displays a warning message if A is badly scaled or nearly singular,
but performs the calculation regardless

Ex:
A = [1 1 3; 2 0 4; -1 6 -1];
B = [2 19 8];
x = B/A
x = 1x3

1.0000 2.0000 3.0000

mldivide, \ - solves systems of linear equations Ax=B for x


Syntax:
X = A\B
X = mldivide(A,B)
Matrices A & B must contain the same number of rows

Ex:
A = [1 2 0; 0 4 3];
B = [8; 18];
x = A\B
X = 3x1

0
4.0000
0.6667

Determinants Using Gauss Elimination:


The determinant for any upper triangular matrix or lower triangular
matrix is the product of diagonal elements.

Since A=LU → det(A)=?


det(A)=det(L)det(U)
L has ones in the main diagonal, so the product of those elements
is 1, resulting in det(L)=1:
det(A)=det(U)

Matrix Inverses Using Gauss Elimination:

inv - matrix inverse


Syntax:
Y = inv(x)
Computes the inverse of square matrix x

Ex: Lab 6
lu - LU matrix factorization
Syntax:
[L,U] = lu(A)
Factorizes the full or sparse matrix A into an upper triangular matrix
U and a permuted lower triangular matrix L such that A = L*U

Ex:
Lecture 14

Solving Ax=b using LU Decomposition:

Forward Substitution:
Consider Ax=b (A is the lower triangular matrix—--nonzero elements)
[a11 0… 0 ][x1] [b1]
[a21 a22… 0 ][x2] = [b2]
… …
[am1 am2… amm][xm] [bm]

Ex:
function x = forwardsub(A,b)
[nr,nc]=size(A)
for i=1:nr
x(i)=b(i);
for j=1:i-1
x(i)=x(i)-A(i,j)*x(j);
end
x(i)=x(i)/A(i,i);
end

Ex: Using built in operator \

—---------------------------------------------------------------
When i=1
x(1)=b(1)
j+1:0 —--> no counting, no loop (x1=b1/a11)
x(1)=x(1)/A(1,1)
—----------------------------------------------------------------
When i=2
x(2)=b(2)
j=1:1
x(2)=x(2)-A(2,1)*x(1)
x(2)=x(2)/A(2,2)
—-----------------------------------------------------------------
When i=3
x(3)=b(3)
i=1:2
x(3)=x(3)-A(3,1)*x(1)-A(3,2)*x(2)
x(3)=x(3)/A(3,3)
Backward Substitution:
Consider Ax=b (A is an upper triangular matrix)

[a11 a12 a13 a14 . . . a1m][x1] = [b1]


[0 a22 a23 a24 . . . a2m][x2] = [b2]
[0 0 a33 a34 . . . a3m][x3] = [b3]
[... ][..]
[... ][..]
[0 0 0 0 . . . amm][xm] = [bm]

xm=bm/amm

Ex:
function x = backsub(A,Y)
[nr,nc]=size(A);
for i=nr:-1:1
x(i)=Y(i);
for j=i+1:nr
x(i)=x(i)-A(i,j)*x(j);
end
x(i)=x(i)/A(i,i)
End

Lecture 15-16

LU Decomp. w/ Partial Pivoting: (Lab 6)


Partial pivoting is the step in which we search the 1st column for the
row that contains the LARGEST absolute value and exchange the rows so
that the largest element in column 1 is at the a11 position
—-> finding P in relation to lab 6

Steps for a 3x3 matrix:


1. Search 1st column for the largest absolute value
2. Switch the row corresponding to the result from step 1 if it’s
not in the 1st row already
3. Perform Gaussian elimination for the 1st column
4. Search 2nd column excluding element a12 for the largest absolute
value
5. Repeat step 2 except if the result from step 4 is not in the 2nd
row already
6. Perform Gaussian elimination for the 2nd column

What does it mean for P?


1. Set P to an identity matrix
2. For any row, substitute in A (the matrix we’re currently working
on). Switch the corresponding row in P
3. Repeat step 2 until Gaussian elimination for A is complete

Ex:
→ 4 is the largest absolute value in 1st column of A
A = [-1 5 -2]
[ 3 0 -6]
[ 4 -2 7]
→ Set P to an identity matrix
P = [ 1 0 0]
[ 0 1 0]
[ 0 0 1]

→ Switch row 3 and 1


A = [ 4 -2 7] R1 = R3
[ 3 0 -6]
[ -1 5 -2] R3 = R1
P = [ 0 0 1] R1=R3
[ 0 1 0]
[ 1 0 0] R3=R1

P x A = A

→ Perform Gaussian Elimination for the 1st column:


[4 -2 7]
R2=R2-¾R1 [0 3/2 -45/4]
R3=R3-(-¼)R1 [0 9/2 1/4]

→ Search 2nd column for largest abs val excluding a12: 9/2
→ Switch row 3 with 2:
[4 -2 7]
[0 9/2 1/4]
[0 3/2 -45/4]

→ Perform Gaussian Elimination for the 2nd column:


[4 -2 7]
[0 9/2 1/4] = U (upper triangular matrix)
R3=R3-⅓R2 [0 0 -67/6]

Ex:
A = [3 -2 5]
[-5 1 -4]
[5 -6 0]

P = [1 0 0]
[0 1 0]
[0 0 1]

Switching row 2 with 1:


A = [-5 1 -4] R1=R2
[3 -2 5] R2=R1
[5 -6 0]

P = [0 1 0] R1=R2
[1 0 0] R2=R1
[0 0 1]
P * A = A

Gaussian Elim:
[-5 1 -4]
R2=R2-(-⅗)R1 [0 -7/5 13/5]
R3=R3-(-1)R1 [0 -5 -4]

Switching row 3 with 2:


A = [-5 1 -4]
[0 -5 -4]
[0 -7/5 13/5]

P = [0 1 0]
[0 0 1]
[1 0 0]

Gaussian Elim (for column 2):


[-5 1 -4]
[0 -5 -4] = U (upper triangular matrix)
R3=R3-(-7/25)R2 [0 0 93/25]

L = [1 0 0] → L = [1 0 0]
[0 1 0] [-1 1 0]
[0 0 1] [-3/5 -7/25 1]

** PA=LU ** —--> general: A=LU (L is permuted)

Matlab Ex:
Lecture 17-20

Interpolation
The goal is to find a polynomial curve that passes through a set of
points; three common types:

● Naive Interpolation
○ Does not give a smooth curve depending on how big the order
is
○ Goes through the points but don’t know what happens in
between
Fit a curve:
2 𝑛
y = 𝑎0 + 𝑎1𝑥 + 𝑎2 𝑥 +... + 𝑎𝑛𝑥

If we substitute 𝑥1; 𝑥2; 𝑥3; etc →


2 𝑛
𝑦1 = 𝑎0 + 𝑎1𝑥1 + 𝑎2 𝑥1 +... + 𝑎𝑛 𝑥1
2 𝑛
𝑦2 = 𝑎0 + 𝑎1𝑥2 + 𝑎2 𝑥2 +... + 𝑎𝑛 𝑥2
2 𝑛
𝑦3 = 𝑎0 + 𝑎1𝑥3 + 𝑎2 𝑥3 +... + 𝑎𝑛 𝑥3
. . .
2 𝑛
𝑦𝑛 = 𝑎0 + 𝑎1𝑥𝑛 + 𝑎2 𝑥𝑛 +... + 𝑎𝑛 𝑥𝑛
● Lagrange Interpolation
● Cubic Spline Interpolation

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy