Borrar filtros
Borrar filtros

My code won't stop looping

1 visualización (últimos 30 días)
Jayden Cavanagh
Jayden Cavanagh el 5 de Jun. de 2021
Respondida: Sulaymon Eshkabilov el 5 de Jun. de 2021
I am running my code and it gives me the answer for the first 7 of 8 ndiv values but won't for the last one. It will get right to the end of the iterations (somewhere just past 6e5) but then restart looping for the nidx=8 so when I pause it I can see the value is somewhere in the 2e5 and then next time it is 252. How do I make this problem stop so it will give me the final all_k value?
Code:
a=25;
b=a;
ndiv=[4,8,16,32,64,128,256,512];
for nidx=1:length(ndiv)
nx=ndiv(nidx);
nz=nx;
x = linspace(0, a, nx);
z = linspace(0, b, nz);
[X, Z] = meshgrid(x,z);
Tnp1 = zeros(nx, nz);
Tnp1(:,1) = 20; % Left boundary
Tnp1(:,end) = 20; % Right boundary
Tnp1(1,:) = 20+380*sin((x*pi)/25)+205*sin((x*5*pi)/25); % Bottom boundary
Tnp1(end,:) = 20; % Top boundary
% Initialise error and set tolerance for convergence
err = 1;
tol = 1e-8;
k=0;
while err > tol
Tn = Tnp1;
k=k+1;
for i = 2:nx-1
for j = 2:nz-1
Tnp1(i,j) = (1/4)*(Tn(i+1,j)+Tn(i-1,j)+Tn(i,j+1)+Tn(i,j-1));
end
end
err = max(abs(Tnp1(:) - Tn(:)));
end
T2 = Tnp1;
k2=k;
all_k(nidx)=k;
end

Respuesta aceptada

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 5 de Jun. de 2021
Here is the correted part of the code.
...
while err > tol
Told = Tnp1;
k=k+1;
for i = 2:nx-1
for j = 2:nz-1
Tnp1(i,j) = (1/4)*(Tnp1(i+1,j)+Tnp1(i-1,j)+Tnp1(i,j+1)+Tnp1(i,j-1));
end
end
err = max(max(abs((Tnp1 - Told)./Tnp1)))*100; % Probably error in "%" would be more appropriate here. Otherwise, 100 can be removed
end
T2 = Tnp1;
k2=k;
all_k(nidx)=k;
end

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by