I am struggling to plot iteration vs error in the matlab code? can anyone help me with this? very much appreciate it.

13 vues (au cours des 30 derniers jours)
This is the code for Jacobi iteration method. i wanted to plot iteration vs error. but i couldn't figure out how to do it?
% Jacobi method for linear equation
function[x,rel_error]=jacobimethod(A, b, x0, tol, iteration)
% Inputs: A - Coefficient matrix
A=[2 -1 0;-1 2 -1;0 -1 2];
% b - Input matrix
b = [0; 2; 0];
x0=[0; 0; 0];
% tol - Defining tolerance for solution
tol=1.e-03;
% iteration - Number of iterations
iteration=10;
% Outputs: x - Solutions
% rel_error - Relative error
D = diag(diag(A)); % Making coefficient matrix diagonal
R = A - D; % Construction of another matrix "R"
N = 1; % iteration counter
x = x0;
rel_error = tol * 2; % norm(x - x0)/norm(x);
exct = A\b;
% Implementation of Jacobi method to solve Ax = b
while (rel_error>tol && N <= iteration)
xprev = x;
x = inv(D)*(b - R*xprev);
rel_error = norm((x - xprev)/x);
er = norm(x-exct)
fprintf('\n Iteration %i: Relative error =%d ',x, rel_error);
N = N + 1;
end

Réponse acceptée

Torsten
Torsten le 24 Nov 2022
Modifié(e) : Torsten le 24 Nov 2022
% Inputs: A - Coefficient matrix
A=[2 -1 0;-1 2 -1;0 -1 2];
% b - Input matrix
b = [0; 2; 0];
% x0 - Initial guess
x0 = [0; 0; 0];
% tol - Defining tolerance for solution
tol=1.e-03;
% iteration - Number of iterations
iteration=10;
[x,Rel_error]=jacobimethod(A, b, x0, tol, iteration);
x
x = 3×1
0.9688 1.9375 0.9688
plot(Rel_error)
% Jacobi method for linear equation
function[x,Rel_error]=jacobimethod(A, b, x0, tol, iteration)
% Outputs: x - Solutions
% rel_error - Relative error
D = diag(diag(A)); % Making coefficient matrix diagonal
R = A - D; % Construction of another matrix "R"
N = 1; % iteration counter
x = x0;
rel_error = tol * 2; % norm(x - x0)/norm(x);
exct = A\b;
% Implementation of Jacobi method to solve Ax = b
while (rel_error>tol && N <= iteration)
xprev = x;
x = inv(D)*(b - R*xprev);
rel_error = norm(x - xprev)/norm(x);
Rel_error(N) = rel_error;
er = norm(x-exct);
%fprintf('\n Iteration %i: Relative error =%d ',N, rel_error);
N = N + 1;
end
end
  4 commentaires
Uma Maheswara Rao Epuganti
Thank you. i do want to plot this for the first 10 iterations. this is only for 10th iteration. could you please tell me how to figure that out?
Walter Roberson
Walter Roberson le 25 Nov 2022
It looks to me as if the full plot is present in Torsten's answer.

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 24 Nov 2022
fprintf('\n Iteration %d: Relative error = %g\n', N, rel_error);

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by