How do I plot the relative error for each iteration vs. iteration number?
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 #');
0 Kommentare
Antworten (1)
Karim
am 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
fprintf('=====================================================\n')
figure
plot(ea_plot)
grid on
title('Error vs. Itteration #')
0 Kommentare
Siehe auch
Kategorien
Mehr zu Surface and Mesh Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!