In: Mechanical Engineering
Using this sample matlab code:
clear all;
clc
A= ????????;
B= ????????;
AUG=[A B];
for L=1:size(A,2)
%Pivoting starts
for k=L:size(AUG,1)
for m=k+1:size(AUG,1)
if abs(AUG(k,L))<abs(AUG(m,L))
temp=AUG(m,:);
AUG(m,:)=?????????;
AUG(k,:)=?????????;
end
end
end
%Pivoting ends
%Gauss Elimination starts
for k=L+1:size(AUG,1)
AUG(k,:)= ????????????????????????????;
AA=AUG(:,1:size(A,2))
BB=AUG(:,size(A,2)+1:end)
end
%Gauss Elimination ends
end
b)Write a MATLAB M-file which performs gauss elimination without pivoting step by step and shows the coefficient matrix in each step. Using cond (X, P) calculate the condition number of the final step coefficient matrix (U matrix).
c) Write a MATLAB M-file which performs gauss elimination with pivoting step by step and shows the coefficient matrix in each step.
d)Using cond (X, P) calculate the condition number of the final step coefficient matrix (U matrix).
clc; clear;
%% Gauss elimination WITHOUT Pivoting
A = [3 1 4; -1 5 2; 3 1 7];
b = [1; 4; 7];
[n, n] = size(A);
% Check for zero diagonal elements
if any(diag(A)==0)
error('Division by zero will occur; pivoting not supported')
end
% Forward elimination
for row=1:n-1
for i=row+1:n
factor = A(i,row) / A(row,row);
for j = row:n
A(i,j) = A(i,j) - factor*A(row,j);
end
b(i) = b(i) - factor*b(row);
end
A_and_b = [A b]
end
% Backward substitution
x(n) = b(n) / A(n,n);
for row = n-1:-1:1
sums = b(row);
for j = row+1: n
sums = sums - A(row,j) * x(j);
end
x(row) = sums / A(row,row);
end
p1 = 1 ;
C1 = cond(A,p1)
%% Gauss elimination WITH Pivoting
A = [3 1 4; -1 5 2; 3 1 7];
b = [1; 4; 7];
% Create permutation vector
n = size(A, 1); % Size of input matrix
r = zeros(n, 1); % Initialize permutation vector
for i = 1 : 1 : n
r(i) = i;
end
% Apply Gaussian elimination and rearrange permutation vector
x = zeros(n, 1); % Initialize solution vector
for k = 1 : 1 : n % Go through each element in permutation vector
% Compare each element in r(k)th column for the max
max = abs(A(r(k), r(k)));
max_pos = k;
for l = k : 1 : n
if abs(A(r(l), r(k))) > max
max = abs(A(r(l), r(k)));
max_pos = l;
end
end
% Switch the kth r-vector element with max r-vector element
temp_r = r;
r(k) = temp_r(max_pos);
r(max_pos) = temp_r(k);
% Eliminate A-vector elements in r(k)th column below r(k)th row
for i = 1 : 1 : n
if i ~= k
zeta = A(r(i), k) / A(r(k), k);
for j = k : 1 : n
A(r(i), j) = A(r(i), j) - A(r(k), j) * zeta;
end
b(r(i)) = b(r(i)) - b(r(k)) * zeta;
end
end
end
% Compute the solution frpm the diagonalized A-matrix
for i = 1 : 1 : n
x(i) = b(r(i)) / A(r(i), i)
end
p2 = 1 ;
C2 = cond(A,p2)