Create a function in MATLAB that finds the unique solution to Ax=b equation usin
ID: 3731132 • Letter: C
Question
Create a function in MATLAB that finds the unique solution to Ax=b equation using Gaussian elimination with partial pivoting where A is a square matrix and b is a column vector of the same height. The function will take A and b as inputs and give x as the output. Partial pivoting is choosing the largest absolute value possible for a diagonal entry within the active column and changing rows accordingly.
Part 1: Start by writing a function (with comments) to achieve these: Determine if the matrix A is square. Augment A and b. Find the maximum absolute value in the first column and the row number that this belongs to using a forloop. Interchange the first row with the row with the maximum firstcolumnentry. (To achieve this, create a short subfunction that interchanges two specified rows for any matrix.) Submit a single mfile with a subfunction that switches rows
Explanation / Answer
Steps:
1. Find the entry in the left column with the largest absolute value. This
entry is called the pivot.
2. Interchange rows, if required , so that the pivot is in the 1st row.
3. Divide the 1st row by the pivot. (This step is unnecessary if the pivot is 1)
4. Use elementary row operations to reduce the remaining entries in the
first column to zero.
The completion of these four steps is called a pass. After performing the
first pass, ignore the first row and first column and repeat the four steps
on the remaining submatrix. Continue this process until the matrix is in
row-echelon form.
Code:
function gaussian_partial
A=input('provide matrix A:');
b=input('provide matrix b:');
gauss(A,b)
end
function x=gauss(A,b)
n = size(A,1); %getting n
A = [A,b]; %produces the augmented matrix
%elimination process starts
for i = 1:n-1
p = i;
%comparison to select the pivot
for j = i+1:n
if abs(A(j,i)) > abs(A(i,i))
U = A(i,:);
A(i,:) = A(j,:);
A(j,:) = U;
end
end
%checking for nullity of the pivots
while A(p,i)== 0 & p <= n
p = p+1;
end
if p == n+1
disp('No unique solution');
break
else
if p ~= i
T = A(i,:);
A(i,:) = A(p,:);
A(p,:) = T;
end
end
for j = i+1:n
m = A(j,i)/A(i,i);
for k = i+1:n+1
A(j,k) = A(j,k) - m*A(i,k);
end
end
end
%checking for nonzero of last entry
if A(n,n) == 0
disp('No unique solution');
return
end
%backward substitution
x(n) = A(n,n+1)/A(n,n);
for i = n - 1:-1:1
sumax = 0;
for j = i+1:n
sumax = sumax + A(i,j)*x(j);
end
x(i) = (A(i,n+1) - sumax)/A(i,i);
end
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.