How do I plot the relative error for each iteration vs. iteration number?

18 views (last 30 days)
How do I plot the relative error for each iteration vs. iteration number? I used Gauss-Seidel to solve the initial problem, but the plot comes up blank. How do I fix this? Thanks!
clear
clc
A = [4 1 2; 3 8 1; 2 3 6];
B = [200 400 300]';
x = ones(1,length(B))';
[m,n] = size(A);
c = zeros(m,n);
d = zeros(m,1);
ea = 100;
tol = 0.000006;
iter = 1;
while ea > tol
for i = 1:n
d(i) = B(i)/A(i,i);
for j = 1:m
if i == j
c(i,j) = 0;
else
c(i,j) = A(i,j)/A(i,i);
end
end
x_new(i) = d(i) - c(i,:)*x(:) ;
ea_vect(i) = abs((x_new(i) - x(i))/x_new(i)*100);
x(i) = x_new(i);
end
ea = max(ea_vect);
fprintf('%d %9.4f %9.4f %9.4f %9.4f\n', iter, x(1),x(2),x(3),ea)
iter = iter + 1;
end
fprintf('=====================================================\n')
hold on
plot(ea,iter)
grid on;
axis ([0 11 0 100])
title('Error vs. Itteration #');

Answers (1)

Karim
Karim on 12 Nov 2022
Hey, you need to save the value in order to plot it. I added an extra variable (ea_plot) to achieve this, see below.
A = [4 1 2; 3 8 1; 2 3 6];
B = [200 400 300]';
x = ones(1,length(B))';
[m,n] = size(A);
c = zeros(m,n);
d = zeros(m,1);
ea = 100;
tol = 0.000006;
iter = 1;
ea_plot = [];
while ea > tol
for i = 1:n
d(i) = B(i)/A(i,i);
for j = 1:m
if i == j
c(i,j) = 0;
else
c(i,j) = A(i,j)/A(i,i);
end
end
x_new(i) = d(i) - c(i,:)*x(:) ;
ea_vect(i) = abs((x_new(i) - x(i))/x_new(i)*100);
x(i) = x_new(i);
end
ea = max(ea_vect);
% store ea for plotting
ea_plot(end+1,1) = ea;
fprintf('%d %9.4f %9.4f %9.4f %9.4f\n', iter, x(1),x(2),x(3),ea)
iter = iter + 1;
end
1 49.2500 31.4062 17.8802 97.9695 2 33.2083 35.3118 21.2746 48.3061 3 30.5347 35.8902 21.8767 8.7560 4 30.0891 35.9820 21.9793 1.4809 5 30.0149 35.9970 21.9965 0.2474 6 30.0025 35.9995 21.9994 0.0413 7 30.0004 35.9999 21.9999 0.0069 8 30.0001 36.0000 22.0000 0.0011 9 30.0000 36.0000 22.0000 0.0002 10 30.0000 36.0000 22.0000 0.0000 11 30.0000 36.0000 22.0000 0.0000
fprintf('=====================================================\n')
=====================================================
figure
plot(ea_plot)
grid on
title('Error vs. Itteration #')

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!