Why doesn't the loop in my for loop work?
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Sai Sri Harsha Vallabhuni
2020-6-30
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
2020-6-30
编辑:Steven Lord
2020-6-30
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
另请参阅
类别
在 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!