MATLAB Answers

# Residual vs Iteration Plot

9 views (last 30 days)
Sam McMillan on 3 May 2021
Commented: Mathieu NOE on 3 May 2021
I'm trying to plot the convergence of when the residual reaches 1e-5 after a certain number of iterations. My figure(1) plot is weird, and doesn't plot a line showing its convergence over the iteration interval. It kind of plots the axes at a specific point, with no line. Please help.
L = 0.05;
T_w = 5;
T_e = 100;
dx = 0.005;
dy = dx;
nx = (L/dx)+1;
ny = nx;
T = T_e*ones(nx,ny);
eq_no = zeros(nx,ny);
max_iter = 10000; % Maximum Iterations
max_res = 1e-5; % Maximum Residual
for n = 1:max_iter
Tn = T; % Previous Nodal Temperature (degC)
for i = 1:nx
for j = 1:ny
if (i > 1 && i < nx && j > 1 && j < ny)
eq_no(i,j) = 1;
T(i,j) = (Tn(i,j+1) + Tn(i,j-1) + Tn(i+1,j) + Tn(i-1,j))/4;
else
eq_no(i,j) = 2;
T(i,j) = T_w;
end
end
end
res = max(abs(T-Tn));
if res < max_res
break
end
end
figure(1)
plot(n,res)
grid
figure(2)
pcolor(T')
shading interp
title('Nodal Temperature Distribution');
xlabel('Horizontal Nodes');
ylabel('Vertical Nodes');
colorbar();
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Mathieu NOE on 3 May 2021
hello
code fixed :
L = 0.05;
T_w = 5;
T_e = 100;
dx = 0.005;
dy = dx;
nx = (L/dx)+1;
ny = nx;
T = T_e*ones(nx,ny);
eq_no = zeros(nx,ny);
max_iter = 10000; % Maximum Iterations
max_res = 1e-5; % Maximum Residual
for n = 1:max_iter
Tn = T; % Previous Nodal Temperature (degC)
for i = 1:nx
for j = 1:ny
if (i > 1 && i < nx && j > 1 && j < ny)
eq_no(i,j) = 1;
T(i,j) = (Tn(i,j+1) + Tn(i,j-1) + Tn(i+1,j) + Tn(i-1,j))/4;
else
eq_no(i,j) = 2;
T(i,j) = T_w;
end
end
end
res(n) = max(abs(T-Tn),[],'all'); % <= correction here
if res(n) < max_res
break
end
end
figure(1)
plot(1:n,res) % <= correction here
grid
figure(2)
pcolor(T')
shading interp
title('Nodal Temperature Distribution');
xlabel('Horizontal Nodes');
ylabel('Vertical Nodes');
colorbar();
##### 2 CommentsShowHide 1 older comment
Mathieu NOE on 3 May 2021
my pleasure !

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!