How can I use a value recursively in for loop
1 次查看(过去 30 天)
显示 更早的评论
Hello everyone,
I have an issue with my code. I want to use recursively the new values of a and b created in if or elseif staments. I thought that I can use a for loop but I couldn't write the boundaries of it. My start position is (20, 70) and my goal position is (60, 40), so when a=60 && b=40 I want to end the code. But as I said the a value and the b value does not gradually increase. For example for a it starts from 20 to 19, later 18, later 19, later 20, later 21, etc. depending on the Utot values. Can you please help me how can I use these values recursively and plot these? Thank you.
a=20;
b=70;
%qstart=[a,b];
A11 = Utot(a-1,b-1);
A21 = Utot(a,b-1);
A31 = Utot(a+1,b-1);
A12 = Utot(a-1,b);
A32 = Utot(a+1,b);
A13 = Utot(a-1,b+1);
A23 = Utot(a,b+1);
A33 = Utot(a+1,b+1);
xd=[A11 A21 A31 A12 A32 A13 A23 A33]
if min(xd) < Utot(a, b)
[minValue, indexOfMinValue] = min(xd)
if min(xd)==A11
plot([a, a-1], [b, b-1])
a=a-1;
b=b-1;
elseif min(xd)==A21
plot([a,a], [b, b-1])
a=a;
b=b-1;
elseif min(xd)==A31
plot([a, a+1], [b, b-1])
a=a+1;
b=b-1;
elseif min(xd)==A12
plot([a, a-1], [b, b])
a=a-1
b=b
elseif min(xd)==A32
plot([a, a+1], [b, b])
a=a+1;
b=b;
elseif min(xd)==A13
plot([a, a-1], [b, b+1])
a=a-1;
b=b+1;
elseif min(xd)==A23
plot([a, a], [b, b+1])
a=a;
b=b+1;
elseif min(xd)==A33
plot([a, a+1], [b, b+1])
a=a+1;
b=b+1;
end
end
0 个评论
采纳的回答
Cris LaPierre
2020-12-20
There is no loop here. As written, your sript will execute just once.
You probably want to use a while loop, which will continue running until the condition is false. Be careful, though. It is very easy to create an infinite loop, meaning your condition is always true so the loop never stops.
a=20;
b=70;
while a~=60 && b~=40
...
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 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!