Clear Filters
Clear Filters

The formula doesn't calculate

2 views (last 30 days)
재훈
재훈 on 12 Apr 2024
Edited: Pooja Kumari on 12 Apr 2024
I am calculating a matrix using Gaussian elimination, but the calculation does not work under the following conditions.
A=[2 0 1; -2 4 1; -1 -1 3] b=[8 ; 0 ;2 ] x=[x1; x2; x3]
I think it doesn't work because there is a 0 in row 1 and column 2 of A. How should I change the code? Have a nice day everyone:)
here is a code
clc; clear all; close all;
A = [2 0 1 ; -2 4 1 ;-1 -1 3];
b = [8 0 2]';
%b = [7; 8 ;3];
sz = size(A,1);
disp ([A b]);
for i = 2 :1: sz
for j = 1:1:i-1
k = A(j,j)/A(i,j);
A(i,:) = k * A(i,:) - A(j,:);
b(i) = k * b(i) - b(j);
disp([A b]);
end
end
for i = sz-1:-1:1
for j = sz:-1:i+1
k = A(j,j)/A(i,j);
A(i,:) = k*A(i,:)-A(j,:);
b(i) = k* b(i) - b(j);
disp([A b]);
end
end
x = b./diag(A);
disp([A b]./diag(A));
disp(x);

Accepted Answer

Pooja Kumari
Pooja Kumari on 12 Apr 2024
Edited: Pooja Kumari on 12 Apr 2024
Hello,
The issue with your code is not because there is a 0 in row 1 and column 2 of A. Key corrections in your code is as follows:
  1. Forward Elimination Corrected: Properly calculates the factor (k) for each element to be eliminated, ensuring correct elimination of elements below the pivot.
  2. Back Substitution Implemented: Solves for variables from the bottom up after converting (A) to an upper triangular form, ensuring accurate calculation of solution vector (x).
clc; clear all; close all;
A = [2 0 1 ; -2 4 1 ;-1 -1 3];
b = [8; 0; 2];
sz = size(A,1);
disp ([A b]);
% Forward elimination
for i = 1:sz-1
for j = i+1:sz
k = A(j,i)/A(i,i);
A(j,:) = A(j,:) - k * A(i,:);
b(j) = b(j) - k * b(i);
end
end
% Back substitution
x = zeros(sz,1); % Initialize solution vector
for i = sz:-1:1
x(i) = (b(i) - A(i,i+1:sz)*x(i+1:sz))/A(i,i);
end
disp(x);
  1 Comment
재훈
재훈 on 12 Apr 2024
wow... you are genius to me. thx for yor help and have a good day. I really appreciate of you. cheerio!

Sign in to comment.

More Answers (0)

Products


Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!