Filter löschen
Filter löschen

Returning and plotting values from while loop results

2 Ansichten (letzte 30 Tage)
Colin
Colin am 3 Mär. 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

Akzeptierte Antwort

G A
G A am 3 Mär. 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

Weitere Antworten (1)

Colin
Colin am 4 Mär. 2012
Thanks this helped and is exactly what I needed

Kategorien

Mehr zu Physical Units 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!

Translated by