필터 지우기
필터 지우기

Returning and plotting values from while loop results

조회 수: 2 (최근 30일)
Colin
Colin 2012년 3월 3일
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

채택된 답변

G A
G A 2012년 3월 3일
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

추가 답변 (1개)

Colin
Colin 2012년 3월 4일
Thanks this helped and is exactly what I needed

카테고리

Help CenterFile Exchange에서 Physical Units에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by