If statement in for loop

조회 수: 1 (최근 30일)
Joe
Joe 2013년 4월 29일
I'm trying to add an if statement in my for loop but am not really sure on how to proceed. I am running through iterations with a for loop but would like to change one a value in the calculations if it does not satisfy a certain condition. The code below is for a Runge-Kutta(RK4) scheme, and what I am trying to do is scale my step size h in the (i + 1)th step if the error in the ith step does not satisfy some bound. I have included the code below, and I apologize for how long it is, I am still fairly new to programming and am still pretty inefficient.
h = .01
epsilon = 10^-5
x = 0:h:5
u = zeros(1, length(x));
u(1) = 1;
k1 = zeros(1, length(x));
k2 = zeros(1, length(x));
k3 = zeros(1, length(x));
k4 = zeros(1, length(x));
for i = (1: length(x) - 1)
k1(i) = (5)*u(i);
k2(i) = (5)*(u(i) + (h/2)*k1(i));
k3(i) = (5)*(u(i) + (h/2)*k2(i));
k4(i) = (5)*(u(i) + h*k3(i));
u(i + 1) = u(i) + (h/6)*(k1(i) + 2*k2(i) + 2*k3(i) + k4(i))
err = abs(exp(x(i)) - u(i + 1));
if err > epsilon
h = ((err/epsilon)^(1/5))*h
end
end
plot(x, u)
So basically I want to know how to implement the if statement with in the for loop.
  댓글 수: 1
Jan
Jan 2013년 4월 30일
편집: Jan 2013년 4월 30일
You forgot to ask a question. What is your problem?
"error" is an important function in Matlab. Shadowing iot by a variable leads to problems frequently.
Omit "h = h", because this is useless. "delta" is not used, so it can be omitted also.

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2013년 4월 30일
Are you sure you want to calculate exp(i)? It is not likely that the step index matters here. What about exp(x(i))?
  댓글 수: 1
Joe
Joe 2013년 4월 30일
Oh sorry my mistake, I changed it to exp(x(i)).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by