If statement in for loop

1 visualizzazione (ultimi 30 giorni)
Joe
Joe il 29 Apr 2013
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 Commento
Jan
Jan il 30 Apr 2013
Modificato: Jan il 30 Apr 2013
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.

Accedi per commentare.

Risposte (1)

Jan
Jan il 30 Apr 2013
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 Commento
Joe
Joe il 30 Apr 2013
Oh sorry my mistake, I changed it to exp(x(i)).

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by