If statement in for loop
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!