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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by