- edit your question and actually upload your complete code (if it is large)
- edit your question and include your code in the text of the question (if it is small). Use the text formatting button above the text box: {} Code.
Repeated using of the for-loop with different steps ...
29 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I use a for loop to solve a problem with a time step. Inside a for-loop there is equation 'X' that depends on the time-step size. This time step is defined outside the for-loop. Upon each iteration a difference between an actual and previous value of 'X'-equation should not exceed a certain value (for example 5). If this value is exceeded the for loop should break iteration and the next value of the time-step should be taken form defined time-step range. After that a for-loop should run again but with a newly chosen time-step value inside.
2 Commenti
Stephen23
il 25 Gen 2015
An explanation is nice, but seeing your code is even better. Please do either of these:
Risposte (1)
Star Strider
il 25 Gen 2015
Modificato: Star Strider
il 25 Gen 2015
I would use a while loop:
a = 1:100;
t_del = 0.5;
b = zeros(1,length(a));
c(1) = 0;
n = 12;
z = 0;
k = 1;
while z < n
k = k + 1;
c(k) = c(k-1) + 2*a(k-1)*t_del;
b(k) = (c(k));
z = diff(b);
end
I am not certain what you want, so you may have to experiment with it.
EDIT —
The likely reason that break does not do what you want it to has to do with the condition in your if statement, and the way MATLAB evaluates conditions on vectors. (Your ‘z’ variable is a vector.)
With one change, this version of your original code works:
a = 1:100;
t_del = 0.5;
b = zeros(1,length(a));
c = 0;
n = 12;
for k = 1:length(a)
c = c + 2*a(k)*t_del;
b(k) = (c);
z = diff(b)
if any(z > n)
break
end
end
7 Commenti
Guillaume
il 26 Gen 2015
continue skips the rest of the body of a for loop and jumps directly to the end statement. Therefore, continue as the last statement in the loop has no effect and is just confusing. Don't do it.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!