How do I plot the relative error for each iteration vs. iteration number?
13 ビュー (過去 30 日間)
表示 古いコメント
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 件のコメント
回答 (1 件)
Karim
2022 年 11 月 12 日
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 件のコメント
参考
カテゴリ
Find more on Vector Fields in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!