0% found this document useful (0 votes)
17 views2 pages

Question 6 Matlab Code

The document contains a MATLAB function for solving a system of linear equations using Gaussian elimination with scaled partial pivoting. It defines the function 'gaussian_elimination_scaled_partial_pivot' which takes a coefficient matrix A and a vector b, performs the elimination process, and then back substitutes to find the solution. An example is provided with a specific matrix A and vector b, resulting in a solution for the variables x1, x2, x3, and x4.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

Question 6 Matlab Code

The document contains a MATLAB function for solving a system of linear equations using Gaussian elimination with scaled partial pivoting. It defines the function 'gaussian_elimination_scaled_partial_pivot' which takes a coefficient matrix A and a vector b, performs the elimination process, and then back substitutes to find the solution. An example is provided with a specific matrix A and vector b, resulting in a solution for the variables x1, x2, x3, and x4.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question 6 Matlab code.

function x = gaussian_elimination_scaled_partial_pivot(A, b)
n = length(b);
% Augment matrix A with vector b
aug_matrix = [A, b];

% Scale factors (max absolute value in each row)


scale_factors = max(abs(A), [], 2);

% Perform Gaussian elimination with scaled partial pivoting


for i = 1:n
% Select the pivot row based on scaled partial pivoting
scaled_pivots = abs(aug_matrix(:, i)) ./ scale_factors;
[~, pivot_row] = max(scaled_pivots(i:n));
pivot_row = pivot_row + i - 1;

if pivot_row ~= i
aug_matrix([i, pivot_row], :) = aug_matrix([pivot_row, i], :);
end

% Eliminate elements below pivot


for j = i+1:n
factor = aug_matrix(j, i) / aug_matrix(i, i);
aug_matrix(j, :) = aug_matrix(j, :) - factor * aug_matrix(i, :);
end
end

% Back substitution
x = zeros(n, 1);
for i = n:-1:1
x(i) = (aug_matrix(i, end) - aug_matrix(i, i+1:n) * x(i+1:n)) / aug_matrix(i,
i);
end
end

% Coefficients matrix A and vector b


A = [-1, 1, 0, -3;
1, 0, 3, 1;
0, 1, -1, -1;
3, 0, 1, 2];

b = [4; 0; 3; 1];

% Solve the system


solution = gaussian_elimination_scaled_partial_pivot(A, b);

% Display the solution


fprintf('Solution:\n');
fprintf('x1 = %.4f\n', solution(1));
fprintf('x2 = %.4f\n', solution(2));
fprintf('x3 = %.4f\n', solution(3));
fprintf('x4 = %.4f\n', solution(4));

Solution:
x1 = 1.0000
x2 = 2.0000
x3 = -0.0000
x4 = -1.0000

You might also like