If statement in for loop

7 次查看(过去 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))?

类别

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