Borrar filtros
Borrar filtros

Returning and plotting values from while loop results

2 visualizaciones (últimos 30 días)
Colin
Colin el 3 de Mzo. de 2012
This is my code so far:
M = 39;
% Number of gridpoints
deltax = 1/(M+1);
% Defines deltax
u = zeros(M,1);
count = 0;
x = 1;
for j = 1:M
m(j) = deltax*j;
b(j) = 6*(deltax^3)*j;
exact(j) = (deltax*j)^3;
end
for r = 1:M
if r == 1
res(r) = b(r) - (u(r+1) - 2*u(r) + 0);
else if r == M
res(r) = b(r) - (1 - 2*u(r) + u(r-1));
else
res(r) = b(r) - (u(r+1) - 2*u(r) + u(r-1));
end
end
end
res0 = norm(res);
residual(1) = res0/res0;
% Defines the initial residual equal to 1
while residual(x) > 1.0e-2
for i = 1:M
if i == 1
d = u(i+1)+0;
else if i == M
d = 1+u(i-1);
else
d = u(i+1) + u(i-1);
end
u(i) = -(1/2)*((b(i)) - d);
end
for r = 1:M
if r == 1
res(r) = b(r) - (u(r+1) - 2*u(r) + 0);
else if r == M
res(r) = b(r) - (1 - 2*u(r) + u(r-1));
else
res(r) = b(r) - (u(r+1) - 2*u(r) + u(r-1));
end
end
resx = norm(res);
residual(x) = resx/res0
end
end
count = count + 1
end
When I run it, it runs the while loop till my residual term drops below the specified value (which is what I want it to do).
My questions is, how can I get it to save all my residual values so I can plot their history (i.e. residual 1, residual 2, ..., to last residual in while loop). I want to plot decreasing residual versus number of iterations but right now my code just returns the last updated residual value. I want it to still do that but also give me all residuals to plot.
Thanks in advance
Colin

Respuesta aceptada

G A
G A el 3 de Mzo. de 2012
I would modify your while loop as:
while residual > 1.0e-2
...
resx = norm(res);
residual = resx/res0;
residualToPlot(count+1)=residual;
end
end
count = count + 1;
end
x as index is redundant

Más respuestas (1)

Colin
Colin el 4 de Mzo. de 2012
Thanks this helped and is exactly what I needed

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by