In: Computer Science
Write a function to solve a system of linear equations of the form Ax= b using the iterative Gauss-Seidel method. You are free to use any basic MATLAB operation to implement the algorithm (i.e. you may use any combination of loops, indexing, math, etc.), but avoid “built-in” solution methods — you would not be allowed to use the GaussSeidel function if such a function existed. The function must also test for a number of possible issues. If an issue is encountered, you should use the error() command to issue a reasonable error message. Use distinct error messages for each of the following cases: • If the dimensions of the input matrices do not conform with each other • If the matrix of coefficients is not square
We need to solve a system of linear equations represented as
The general Gauss-Seidel algorithm for this system of equation is written as,
where for k =0, vector is known. a is the element of matrix A. bi is the element of vector b. i represents the row and j represents the column.
MATLAB code.
clc;clear; close all; %% Take the input A = input('Enter the matrix of coefficients, A: ') % Check for error [row_A, column_A] = size(A); if row_A ~= column_A error('Matrix of coeffecient is not square.') end b = input('Enter the column vector, b: ') % Check for error [row_b, column_b] = size(b) if column_A ~=size(b) error('Dimension of input matrices do not confirm with each other.') end x0 = input('Enter the initial guess vector, x0 :') nItr = input('Enter the max no. of iterations :') %% Gauss-Seidel iterations for k=1:nItr % k=>iteration for i=1:length(b) % i=>unknown x(i,1) = (b(i)/A(i,i)) - (A(i,[1:i-1, i+1:length(b)])*x0([1:i-1, i+1:length(b)]))/... A(i,i); x0(i,1) = x(i,1); % update to use for next unknown(xi) end fprintf('Iteration no. %d\n', k) x end