Mathematical Lab PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

COMPUTATIONAL MATHEMATICS LAB

1. Python code for solving a system of linear equation using Gauss Elimination
Method
defgauss(A):
m =len(A)
assertall([len(row) == m +1for row inA[1:]]), "Matrix rows have non-uniform
length"
n = m +1
for kinrange(m):
pivots = [abs(A[i][k]) foriinrange(k, m)]
i_max=pivots.index(max(pivots)) + k
# Check for singular matrix
assertA[i_max][k] !=0, "Matrix is singular!"
# Swap rows
A[k], A[i_max] =A[i_max], A[k]

foriinrange(k +1, m):


f =A[i][k] /A[k][k]
for j inrange(k +1, n):
A[i][j] -=A[k][j] * f

# Fill lower triangular matrix with zeros:


A[i][k] =0
# Solve equation Ax=b for an upper triangular matrix A
x = []
foriinrange(m -1, -1, -1):
x.insert(0, A[i][m] /A[i][i])
for kinrange(i-1, -1, -1):
A[k][m] -=A[k][i] *x[0]
return x

1.Generate a MATLAB code for solving a system of linear equation using Gauss
Elimination method.
% Matlab Program to solve (nxn) system equation
% by using Gaussian Elimination method
clear ; clc ; close all
n = input('Please Enter the size of the equation system n = ') ;
C = input('Please Enter the elements of the Matrix C ' ) ;
b = input('Please Enter the elements of the Matrix b ' ) ;
dett = det(C)
if dett == 0
print('This system unsolvable because det(C) = 0 ')
else
b = b'
A=[C b]
for j = 1:(n-1)
for i= (j+1) : n
mult = A(i,j)/A(j,j) ;
for k= j:n+1
A(i,k) = A(i,k) - mult*A(j,k) ;
A
end
end
end
for p = n:-1:1
for r = p+1:n
x(p) = A(p,r)/A(p,r-1)
end
end
end

Problem:
x1 + 2x2 - x3 = 3
2x1 + x2 - 2x3 = 3
-3x1 + x2 + x3 = -6
C = [ 1 2 -1 ; 2 1 -2 ; -3 1 1 ]
b= [ 3 3 -6 ]

Output:
Please Enter the size of the equation system n = 3
Please Enter the elements of the Matrix C [ 1 2 -1 ; 2 1 -2 ; -3 1 1 ]
Please Enter the elements of the Matrix b [ 3 3 -6 ]

dett =

6.0000
b=
3
3
-6
A=
1 2 -1 3
2 1 -2 3
-3 1 1 -6
A=
1 2 -1 3
0 1 -2 3
-3 1 1 -6

A=
1 2 -1 3
0 -3 -2 3
-3 1 1 -6
A=
1 2 -1 3
0 -3 0 3
-3 1 1 -6
A=
1 2 -1 3
0 -3 0 -3
-3 1 1 -6
A=
1 2 -1 3
0 -3 0 -3
0 1 1 -6
A=
1 2 -1 3
0 -3 0 -3
0 7 1 -6
A=
1 2 -1 3
0 -3 0 -3
0 7 -2 -6
A=
1 2 -1 3
0 -3 0 -3
0 7 -2 3
A=
1 2 -1 3
0 -3 0 -3
0 0 -2 3
A=
1 2 -1 3
0 -3 0 -3
0 0 -2 3
A=
1 2 -1 3
0 -3 0 -3
0 0 -2 -4

2.Python code for LU Decomposition (Factorization)


importpprint

defmult_matrix(M, N):
"""Multiply square matrices of same dimension M and N"""

# Converts N into a list of tuples of columns


tuple_N=zip(*N)

# Nested list comprehension to calculate matrix multiplication


return[[sum(el_m*el_nforel_m,el_ninzip(row_m,col_n))forcol_nintuple_N]forrow_
min M]

defpivot_matrix(M):
"""Returns the pivoting matrix for M, used in Doolittle's method."""
m =len(M)

# Create an identity matrix, with floating point values


id_mat=[[float(i==j)foriinxrange(m)]for j inxrange(m)]

# Rearrange the identity matrix such that the largest element of


# each column of M is placed on the diagonal of of M
for j inxrange(m):
row =max(xrange(j, m), key=lambda i:abs(M[i][j]))
ifj != row:
# Swap the rows
id_mat[j],id_mat[row]=id_mat[row],id_mat[j]

returnid_mat

deflu_decomposition(A):
"""Performs an LU Decomposition of A (which must be square)
into PA = LU. The function returns P, L and U."""
n =len(A)

# Create zero matrices for L and U


L =[[0.0]* n foriinxrange(n)]
U =[[0.0]* n foriinxrange(n)]

# Create the pivot matrix P and the multipled matrix PA


P =pivot_matrix(A)
PA =mult_matrix(P, A)

# Perform the LU Decomposition


for j inxrange(n):
# All diagonal entries of L are set to unity
L[j][j]=1.0

# LaTeX: u_{ij} = a_{ij} - \sum_{k=1}^{i-1} u_{kj} l_{ik}


foriinxrange(j+1):
s1 =sum(U[k][j]* L[i][k]for kinxrange(i))
U[i][j]= PA[i][j]- s1

# LaTeX: l_{ij} = \frac{1}{u_{jj}} (a_{ij} - \sum_{k=1}^{j-1} u_{kj} l_{ik} )


foriinxrange(j, n):
s2 =sum(U[k][j]* L[i][k]for kinxrange(j))
L[i][j]=(PA[i][j]- s2)/ U[j][j]

return(P, L, U)

A =[[7,3,-1,2],[3,8,1,-4],[-1,1,4,-1],[2,-4,-1,6]]
P, L, U =lu_decomposition(A)

print"A:"
pprint.pprint(A)

print"P:"
pprint.pprint(P)

print"L:"
pprint.pprint(L)

print"U:"
pprint.pprint(U)
The output from the pure Python implementation is given below:
A:
[[7, 3, -1, 2], [3, 8, 1, -4], [-1, 1, 4, -1], [2, -4, -1, 6]]
P:
[[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]]
L:
[[1.0, 0.0, 0.0, 0.0],
[0.42857142857142855, 1.0, 0.0, 0.0],
[-0.14285714285714285, 0.2127659574468085, 1.0, 0.0],
[0.2857142857142857, -0.7234042553191489, 0.0898203592814371,
1.0]]
U:
[[7.0, 3.0, -1.0, 2.0],
[0.0, 6.714285714285714, 1.4285714285714286, -
4.857142857142857],
[0.0, 0.0, 3.5531914893617023, 0.31914893617021267],
[0.0, 0.0, 0.0, 1.88622754491018]]
None

2. Generate a MATLAB code for LU Decomposition method.


clc; clear all;close all;
A = [1 3 4 8
2123
4358
9 2 7 4];
B = [1
1
1
1];
matrixSize=length(A);
Lower=zeros(size(A));
Upper=zeros(size(A));

Lower(:,1)= A(:,1); %Set the first column of L to the frist column of A


Upper(1,:)=A(1,:)/Lower(1,1); % Create the first row of upper, divide by L(1,1)

Upper(1,1)=1; % Start the identity matrix


for k=2:matrixSize
for j=2:matrixSize
for i=j:matrixSize
Lower(i,j)=A(i,j) - dot(Lower(i,1:j-1),Upper(1:j-1,j));
end
Upper(k,j)=(A(k,j)-dot(Lower(k,1:k-1),Upper(1:k-1,j)))/Lower(k,k);
end
end
Upper
Lower
%L*Y=B
Y = zeros(matrixSize, 1);
% BASE CASE, SOLVE THE FIRST ONE
Y(1) = B(1);
for row = 2 : matrixSize %2 - number or rows
Y(row) = B(row);
for col = 1 : row - 1 %1 - row number
Y(row) = Y(row) - Lower(row, col) * Y(col);
end
Y(row) = Y(row) / Lower(row, row)
end
Y
%U*X=Y
X = zeros(matrixSize, 1);

X(matrixSize) = Y(matrixSize) / Upper(matrixSize,matrixSize);

for row = matrixSize - 1 : -1 : 1 %second to last row - 1


temp = 0;
for col = matrixSize : -1 : 1 %number of rows to row
temp = temp + Upper(row,col) * X(col);
end
X(row) = (Y(row) - temp) / Upper(row,row);
end
Output:
Upper =

1.0000 3.0000 4.0000 8.0000

0 1.0000 1.2000 2.6000

0 0 1.0000 3.0000

0 0 0 1.0000

Lower =

1.0000 0 0 0

2.0000 -5.0000 0 0

4.0000 -9.0000 -0.2000 0

9.0000 -25.0000 1.0000 -6.0000

Y=

1.0000

0.2000

Y=

1.0000

0.2000

6.0000

Y=
1.0000

0.2000

6.0000

1.5000

Y=

1.0000

0.2000

6.0000

1.5000

3.Python code for Iterative methods to solve equations using Jacobi Iteration.

from pprint import pprint

from numpy import array, zeros, diag, diagflat, dot

def jacobi(A,b,N=25,x=None):

"""Solves the equation Ax=b via the Jacobi iterative method."""

# Create an initial guess if needed

if x is None:

x = zeros(len(A[0]))

# Create a vector of the diagonal elements of A

# and subtract them from A

D = diag(A)

R = A - diagflat(D)

# Iterate for N times

for i in range(N):
x = (b - dot(R,x)) / D

return x

A = array([[2.0,1.0],[5.0,7.0]])

b = array([11.0,13.0])

guess = array([1.0,1.0])

sol = jacobi(A,b,N=25,x=guess)

print "A:"

pprint(A)

print "b:"

pprint(b)

print "x:"

pprint(sol)

Output:

A:

array([[ 2., 1.],

[ 5., 7.]])

b:

array([ 11., 13.])

x:

array([ 7.11110202, -3.22220342])

3. Generate a MATLAB code for Iterative methods to solve equations using Jacobi
Iteration
Program:
clc;clear all;close all
syms x y z
jacobian([x*y*z, y^2, x + z], [x, y, z])

Output:
[ y*z, x*z, x*y]
[ 0, 2*y, 0]
[ 1, 0, 1]
%first column output is differentiate with respect to x
%second column output is differentiate with respect to y
%third column output is differentiate with respect to z

Example: Differentiate with respect to x


jacobian([x*y*z, y^2, x + z], [x])
ans =
y*z
0
1
4.Python code for Curve fitting
i. Straight line fit ii. Polynomial Curve fit
1.
import numpy as np

# curve-fit() function imported from scipy

from scipy.optimize import curve_fit

from matplotlib import pyplot as plt

# numpy.linspace with the given arguments

# produce an array of 40 numbers between 0

# and 10, both inclusive

x = np.linspace(0, 10, num = 40)


# y is another array which stores 3.45 times

# the sine of (values in x) * 1.334.

# The random.normal() draws random sample

# from normal (Gaussian) distribution to make

# them scatter across the base line

y = 3.45 * np.sin(1.334 * x) + np.random.normal(size = 40)

# Test function with coefficients as parameters

def test(x, a, b):

return a * np.sin(b * x)

# curve_fit() function takes the test-function

# x-data and y-data as argument and returns

# the coefficients a and b in param and

# the estimated covariance of param in param_cov

param, param_cov = curve_fit(test, x, y)

print("Sine funcion coefficients:")

print(param)

print("Covariance of coefficients:")

print(param_cov)

# ans stores the new y-data according to

# the coefficients given by curve-fit() function

ans = (param[0]*(np.sin(param[1]*x)))

'''Below 4 lines can be un-commented for plotting results

using matplotlib as shown in the first example. '''

# plt.plot(x, y, 'o', color ='red', label ="data")

# plt.plot(x, ans, '--', color ='blue', label ="optimized data")

# plt.legend()
# plt.show()

Output:

Sine function coefficients:


[ 3.66474998 1.32876756]
Covariance of coefficients:
[[ 5.43766857e-02 -3.69114170e-05]
[ -3.69114170e-05 1.02824503e-04]]

4.Generate a MATLAB code for Curve fitting

Program 1:
% cdate is a column vector containing the years 1790 to 1990 in 10-year
increments.
% pop is a column vector with the U.S. population figures that correspond to
the years in cdate .
plot( cdate, pop, 'o' )
[population2, gof] = fit( cdate, pop, 'poly2' );
figure
plot( population2, cdate, pop );
% Move the legend to the top left corner.
legend( 'Location', 'NorthWest' );

Output:
Figure: Plotting Data

Figure: Polynomial Curve Fitted Data


Program 2:
population3 = fit( cdate, pop, 'poly3', 'Normalize', 'on' );
plot( cdate, pop, 'o' );

plot( population3, 'predobs' )

Fig: Normalization of data

5. Generate a MATLAB program for Fourier Transform


Program:
x=[1 2 3 4];
fft(x)
Output:
10.0000 + 0.0000i -2.0000 + 2.0000i -2.0000 + 0.0000i -2.0000 - 2.0000i

6. Python code for Euler’s method differential equations

# Euler method python program

# function to be solved
deff(x,y):
returnx+y

# or
# f = lambda x: x+y
# Euler method
defeuler(x0,y0,xn,n):

# Calculating step size


h =(xn-x0)/n

print('\n-----------SOLUTION-----------')
print('------------------------------')
print('x0\ty0\tslope\tyn')
print('------------------------------')
foriinrange(n):
slope =f(x0, y0)
yn= y0 + h * slope
print('%.4f\t%.4f\t%0.4f\t%.4f'%(x0,y0,slope,yn))
print('------------------------------')
y0 =yn
x0 = x0+h

print('\nAt x=%.4f, y=%.4f'%(xn,yn))

# Inputs
print('Enter initial conditions:')
x0 =float(input('x0 = '))
y0 =float(input('y0 = '))

print('Enter calculation point: ')


xn=float(input('xn = '))

print('Enter number of steps:')


step =int(input('Number of steps = '))

# Euler method call


euler(x0,y0,xn,step)

Output
Enter initial conditions:
x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 10

-----------SOLUTION-----------
------------------------------
x0 y0 slope yn
------------------------------
0.0000 1.0000 1.0000 1.1000
------------------------------
0.1000 1.1000 1.2000 1.2200
------------------------------
0.2000 1.2200 1.4200 1.3620
------------------------------
0.3000 1.3620 1.6620 1.5282
------------------------------
0.4000 1.5282 1.9282 1.7210
------------------------------
0.5000 1.7210 2.2210 1.9431
------------------------------
0.6000 1.9431 2.5431 2.1974
------------------------------
0.7000 2.1974 2.8974 2.4872
------------------------------
0.8000 2.4872 3.2872 2.8159
------------------------------
0.9000 2.8159 3.7159 3.1875
------------------------------

At x=1.0000, y=3.1875

6. Generate a MATLAB program for Eulers Method differential Equations


Program:
% euler(n) returns the nth Euler number
% euler(n,x) returns the nth Euler polynomial.
syms n x
diff(euler(n,x^2), x)

Output:
2*n*x*euler(n - 1, x^2)

7. Python code for Runge – Kutta method differential equations


# RK-4 method python program

# function to be solved
deff(x,y):
returnx+y

# or
# f = lambda x: x+y

# RK-4 method
defrk4(x0,y0,xn,n):

# Calculating step size


h =(xn-x0)/n

print('\n--------SOLUTION--------')
print('-------------------------')
print('x0\ty0\tyn')
print('-------------------------')
foriinrange(n):
k1 = h *(f(x0, y0))
k2 = h *(f((x0+h/2),(y0+k1/2)))
k3 = h *(f((x0+h/2),(y0+k2/2)))
k4 = h *(f((x0+h),(y0+k3)))
k =(k1+2*k2+2*k3+k4)/6
yn= y0 + k
print('%.4f\t%.4f\t%.4f'%(x0,y0,yn))
print('-------------------------')
y0 =yn
x0 = x0+h

print('\nAt x=%.4f, y=%.4f'%(xn,yn))

# Inputs
print('Enter initial conditions:')
x0 =float(input('x0 = '))
y0 =float(input('y0 = '))

print('Enter calculation point: ')


xn=float(input('xn = '))

print('Enter number of steps:')


step =int(input('Number of steps = '))
# RK4 method call
rk4(x0,y0,xn,step)

Output

Enter initial conditions:


x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 2

--------SOLUTION--------
-------------------------
x0 y0 yn
-------------------------
0.0000 1.0000 1.7969
-------------------------
0.5000 1.7969 3.4347
-------------------------

At x=1.0000, y=3.4347

7. Generate a MATLAB program for Runge-Kutte Method differential Equations


Program:
function [x, y] = FunctionBeta_Executor(F)
% Note that F function expression is defined via Function Handle: F = @(x,
y)(x+y)
% change the function as you desire
h=0.15; % step size (smaller step
size gives more accurate solutions)
x = 0:h:3; % x space
y = zeros(1,length(x)); % Memory allocation
y(1) = 5; % initial condition
for i=1:(length(x)-1)
% i=1:(length(x)-1) % calculation loop
k1 = F(x(i),y(i));
k2 = F(x(i)+0.5*h,y(i)+0.5*h*k1);
k3 = F((x(i)+0.5*h),(y(i)+0.5*h*k2));
k4 = F((x(i)+h),(y(i)+k3*h));
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h; % main equation
end
figure, plot(x, y) % To see the solution results
end
Input:
FunctionBeta_Executor (@(x, y)(x+y))
Input function f(x)= (x, y)(x+y)

Output:
8 Python code for Matrices and Eigen values i. Eigen values and Eigen vectors ii. Jacobi
method
from numpy.linalg import eig

import numpy as np

a=np.array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])

values , vectors = eig(a)

print(values)

print(vectors)

Output 1:

Eigen Values

[ 6.96947758e+01 -3.22806629e+00 -4.66709488e-01 -3.59740472e-14]


Output 2:

Eigen Vectors

[[-6.28224280e-01 -7.67762260e-01 -5.75701703e-01 -4.08248290e-01]


[-7.35387665e-02 -1.62230993e-02 7.06561093e-01 8.16496581e-01]
[-2.05200662e-01 6.09975078e-01 2.05319101e-01 -4.08248290e-01]
[-7.46872808e-01 -1.95469507e-01 -3.56627310e-01 -2.73218204e-14]]

ii.import numpy as np

v = np.zeros ( [ n, n ] )
d = np.zeros ( n )

for j in range ( 0, n ):
for i in range ( 0, n ):
v[i,j] = 0.0
v[j,j] = 1.0

for i in range ( 0, n ):
d[i] = a[i,i]

bw = np.zeros ( n )
zw = np.zeros ( n )
w = np.zeros ( n )

for i in range ( 0, n ):
bw[i] = d[i]

it_num = 0
rot_num = 0

while ( it_num<it_max ):

it_num = it_num + 1
#
# The convergence threshold is based on the size of the elements in
# the strict upper triangle of the matrix.
#
thresh = 0.0
for j in range ( 0, n ):
for i in range ( 0, j ):
thresh = thresh + a[i,j] ** 2

thresh = np.sqrt ( thresh ) / float ( 4 * n )

if ( thresh == 0.0 ):
break

for p in range ( 0, n ):
for q in range ( p + 1, n ):

gapq = 10.0 * abs ( a[p,q] )


termp = gapq + abs ( d[p] )
termq = gapq + abs ( d[q] )
#
# Annihilate tiny offdiagonal elements.
#
if ( 4<it_num and termp == abs ( d[p] ) and termq == abs ( d[q] ) ):

a[p,q] = 0.0
#
# Otherwise, apply a rotation.
#
elif( thresh<= abs ( a[p,q] ) ):

h = d[q] - d[p]
term = abs ( h ) + gapq

if ( term == abs ( h ) ):
t = a[p,q] / h
else:
theta = 0.5 * h / a[p,q]
t = 1.0 / ( abs ( theta ) + np.sqrt ( 1.0 + theta * theta ) )
if ( theta< 0.0 ):
t = - t

c = 1.0 / np.sqrt ( 1.0 + t * t )


s = t * c
tau = s / ( 1.0 + c )
h = t * a[p,q]
#
# Accumulate corrections to diagonal elements.
#
zw[p] = zw[p] - h
zw[q] = zw[q] + h
d[p] = d[p] - h
d[q] = d[q] + h

a[p,q] = 0.0
#
# Rotate, using information from the upper triangle of A only.
#
for j in range ( 0, p ):
g = a[j,p]
h = a[j,q]
a[j,p] = g - s * ( h + g * tau )
a[j,q] = h + s * ( g - h * tau )

for j in range ( p + 1, q ):
g = a[p,j]
h = a[j,q]
a[p,j] = g - s * ( h + g * tau )
a[j,q] = h + s * ( g - h * tau )

for j in range ( q + 1, n ):
g = a[p,j]
h = a[q,j]
a[p,j] = g - s * ( h + g * tau )
a[q,j] = h + s * ( g - h * tau )
#
# Accumulate information in the eigenvector matrix.
#
for j in range ( 0, n ):
g = v[j,p]
h = v[j,q]
v[j,p] = g - s * ( h + g * tau )
v[j,q] = h + s * ( g - h * tau )

rot_num = rot_num + 1

for i in range ( 0, n ):
bw[i] = bw[i] + zw[i]
d[i] = bw[i]
zw[i] = 0.0
#
# Restore upper triangle of input matrix.
#
for j in range ( 0, n ):
for i in range ( 0, j ):
a[i,j] = a[j,i]
#
# Ascending sort the eigenvalues and eigenvectors.
#
for k in range ( 0, n - 1 ):

m = k
for l in range ( k + 1, n ):
if ( d[l] < d[m] ):
m = l

if ( k != m ):

t = d[m]
d[m] = d[k]
d[k] = t

for i in range ( 0, n ):
w[i] = v[i,m]
v[i,m] = v[i,k]
v[i,k] = w[i]

return v, d, it_num, rot_num

def jacobi_eigenvalue_test01 ( ):

#****************************************************************************
*80
#
## JACOBI_EIGENVALUE_TEST01 uses a 4x4 test matrix.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 25 September 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform

n = 4

a = np.array ( [ \
[ 4.0, -30.0, 60.0, -35.0, ], \
[ -30.0, 300.0, -675.0, 420.0, ], \
[ 60.0, -675.0, 1620.0, -1050.0, ], \
[ -35.0, 420.0, -1050.0, 700.0 ] ] )

print ( '' )
print ( 'JACOBI_EIGENVALUE_TEST01' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' JACOBI_EIGENVALUE computes the eigenvalues D' )
print ( ' and eigenvectors V of a symmetric matrix A so that A * V = D *
V.' )

r8mat_print ( n, n, a, ' Input matrix A:' )

it_max = 100

v, d, it_num, rot_num = jacobi_eigenvalue( n, a, it_max )

print ( '' )
print ( ' Number of iterations = %d' % ( it_num ) )
print ( ' Number of rotations = %d' % ( rot_num ) )

r8vec_print ( n, d, ' Eigenvalues D:' )

r8mat_print ( n, n, v, ' Eigenvector matrix V:' )


#
# Compute eigentest.
#
error_frobenius = r8mat_is_eigen_right ( n, n, a, v, d )
print ( '' )
print ( 'Frobenius norm error in eigensystem A*V-D*V = %g' % (
error_frobenius ) )
#
# Terminate.
#
print ( '' )
print ( 'JACOBI_EIGENVALUE_TEST01' )
print ( ' Normal end of execution.' )
return

def jacobi_eigenvalue_test02 ( ):
Output:
JACOBI_EIGENVALUE_TEST
Python version: 3.6.5
Test the JACOBI_EIGENVALUE library.

JACOBI_EIGENVALUE_TEST01
Python version: 3.6.5
JACOBI_EIGENVALUE computes the eigenvalues D
and eigenvectors V of a symmetric matrix A so that A * V = D * V.

Input matrix A:

Col: 0 1 2 3
Row
0 : 4 -30 60 -35
1 : -30 300 -675 420
2 : 60 -675 1620 -1050
3 : -35 420 -1050 700

Number of iterations = 11
Number of rotations = 21

Eigenvalues D:

0: 0.166643
1: 1.47805
2: 37.1015
3: 2585.25

Eigenvector matrix V:

Col: 0 1 2 3
Row
0 : 0.792608 0.582076 0.179186 0.0291933
1 : 0.451923 -0.370502 -0.741918 -0.328712
2 : 0.322416 -0.509579 0.100228 0.791411
3 : 0.252161 -0.514048 0.638283 -0.514553

Frobenius norm error in eigensystem A*V-D*V = 1.20349e-12

JACOBI_EIGENVALUE_TEST01
Normal end of execution.

8. Generate a MATLAB program for Eigen values and Eigen Vectors


Program 1:
a=[1 2 3;4 5 6;7 8 9]
b=eig(a)
[V,D,W]=eig(a
Output:
a=
1 2 3
4 5 6
7 8 9
b=
16.1168
-1.1168
-0.0000
b=Eigen Values of matrix a

V=
-0.2320 -0.7858 0.4082
-0.5253 -0.0868 -0.8165
-0.8187 0.6123 0.408
D=
16.1168 0 0
0 -1.1168 0
0 0 -0.0000
W=
-0.4645 -0.8829 0.4082
-0.5708 -0.2395 -0.8165
-0.6770 0.4039 0.4082

D is a diagonal matrix containing the eigen values.


V is a matrix whose columns are the corresponding right eigenvectors.
W, a matrix whose columns are the corresponding left eigenvectors
Program 2:
syms x y z
jacobian([x*y*z, y^2, x + z], [x, y, z])
Output:
[ y*z, x*z, x*y]
[ 0, 2*y, 0]
[ 1, 0, 1]
9. Generate a MATLAB program for Partial Differential Equations
m = 0;
x = linspace(0,1,20);
t = linspace(0,2,5);

sol = pdepe(m,@pdex1pde,@pdex1ic,@pdex1bc,x,t);
% pdepe is command for Partial DE
% Extract the first solution component as u.
u = sol(:,:,1);

% A surface plot is often a good way to study a solution.


surf(x,t,u)
title('Numerical solution computed with 20 mesh points.')
xlabel('Distance x')
ylabel('Time t')

% A solution profile can also be illuminating.


figure
plot(x,u(end,:))
title('Solution at t = 2')
xlabel('Distance x')
ylabel('u(x,2)')

Output:

You might also like