mirror of
https://github.com/kuhyx/WUT_Computer_Science.git
synced 2026-07-06 21:43:14 +02:00
43 lines
1.6 KiB
Plaintext
43 lines
1.6 KiB
Plaintext
function x = jacobiMethod(Matrix, Vector)
|
|
[Rows,~] = size(Matrix);
|
|
D = diag(diag(Matrix));
|
|
inverseD = inv(D);
|
|
U = triu(Matrix, 1); % Generates upper triangular part of matrix
|
|
% where the second variable denotes on which diagonal of matrix should we
|
|
% start
|
|
L = tril(Matrix, -1); % Generates lower triangular part of matrix
|
|
% where the second variable denotes on which diagonal of matrix should we
|
|
% start
|
|
initial_x = ones(Rows, 1);
|
|
initial_x = - inverseD * ( ( L + U ) * initial_x) + inverseD * initial_x; % As per formula
|
|
% We will be using D \ initial_x and D \ () since it is faster and more
|
|
% accurate according to matlab
|
|
whichIterationAreWeOn = 0;
|
|
currentError = inf; % We set it to inf so that it the algorithm will always start
|
|
% (See condition below)
|
|
demandedTolerance = 1e-10;
|
|
while currentError >= demandedTolerance
|
|
|
|
x = - inverseD * ( ( L + U ) * initial_x) + inverseD * initial_x; % As per formula
|
|
|
|
currentError = norm(x - initial_x);
|
|
disp(currentError);
|
|
if currentError <= demandedTolerance
|
|
currentError = norm(Matrix*x-Vector);
|
|
disp(currentError);
|
|
if currentError <= demandedTolerance
|
|
break;
|
|
else
|
|
demandedTolerance = demandedTolerance * 2;
|
|
end
|
|
end
|
|
initial_x = x;
|
|
whichIterationAreWeOn = whichIterationAreWeOn + 1;
|
|
end
|
|
disp("Final demandedTolerance");
|
|
disp(demandedTolerance);
|
|
disp("Final Iteration: ");
|
|
disp(whichIterationAreWeOn);
|
|
disp("A\b matlab:");
|
|
disp(Matrix / Vector);
|
|
end |