Why doesn't the loop in my for loop work?
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi!
Im trying to get a for-loop to work with an if-statement, but I can't seem to get it to loop at all. Please help!
The snippet of the code that doesn't loop is bellow and Im sorry that the names are in swedish but it shouldn't be a problem...
The "besparingslistan" is a list with 3 coulmns and I want the for loop "f" to loop through all rows in it but only the first column, the same with "a" but only the second column. I don't know if I'm doing the for loops wrong in the beginning or if it just isn't working with "f=f+1" and "a=a+1" at the end.
If the "if-statement" is false, I want the loop to continue to the next row in the "besparingslistan" and therefore don't save anything in the "turkonfig".
for f = 1:Besparingslistan(:,1)
for a = 1:Besparingslistan(:,2)
if Kund_i_tur(f)~= Kund_i_tur(a)
Turkonfig = {f a};
else
f=f+1;
a=a+1;
end
end
end
0 Commenti
Risposte (2)
Sai Sri Harsha Vallabhuni
il 30 Giu 2020
Hey,
Below is modified code which achieves what you are tying to do
for f = Besparingslistan(:,1)
for a = Besparingslistan(:,2)
if Kund_i_tur(f)~= Kund_i_tur(a)
Turkonfig = {f a};
end
end
end
Hope this helps.
Steven Lord
il 30 Giu 2020
Modificato: Steven Lord
il 30 Giu 2020
for f = 1:Besparingslistan(:,1)
This doesn't do what you think it does. Consider:
A = [20 1 2; 2 3 4; 3 4 5; 4 5 6];
for f = 1:A(:, 1)
disp("A(" + f + ", 1) is " + A(f, 1))
end
You will receive an error when f is 5, since A only has 4 rows. Instead of using the values in A to set the limits of your for loop, use the size of A.
A = [20 1 2; 2 3 4; 3 4 5; 4 5 6];
numberOfRows = size(A, 1);
for f = 1:numberOfRows
disp("A(" + f + ", 1) is " + A(f, 1))
end
Also, making changes to the loop variable inside the loop is discouraged. It doesn't do what you want anyway; any changes you made to that loop variable are thrown away when the next iteration of the loop starts and MATLAB takes the next value in the vector.
for k = 1:10
disp("k before changing is " + k)
k = 42;
disp("k after changing is " + k)
end
Vedere anche
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!