Create a single for loop for multiple conditions
显示 更早的评论
Hi, I have a for loop with several calculations. There are three conditions for which the calculations are more or less the same. How can I formulate the code so that I have just one for loop for multiple conditions ? Ex. A same set of speed calculations for a boat a) Moving in still water b) Moving with the current c) Moving against the current
8 个评论
Birdman
2018-1-31
Why don't you share the code? How can we help you without seeing the code?
Birdman
2018-1-31
What is your condition in this cases?
DIP
2018-1-31
Moritz
2018-1-31
I have to say I don't see any difference between the different cases. Can you pin point it to me? Anyhow, why don't you use one for loop and a switch case within for the differences in calculations (alternatively an if else structure as there are only 3 different cases). Does this help?
RobF
2018-1-31
I also have to say that your conditions (still river - downstream - upstream) don't seem to change anything concerning the for loop. Where the point where the condition gets relevant?
DIP
2018-2-1
Walter Roberson
2018-2-1
"the speeds are different"
Not in the code you posted.
回答(1 个)
A. Sawas
2018-2-1
I suggest you use switch statement like this:
Boat_Speed=40;
% set the following variable based on the current water conditions
water_condition = 'Still River';
for i=1:41
% your code before calculating the speed
% calculate vehicle speed at different water conditions
switch water_condition
case 'Still River'
% your code to calculate speed in still river conditions
case 'Downstream'
% your code to calculate speed in downstream conditions
case 'Upstream'
% your code to calculate speed in upstream conditions
otherwise
warning('Unexpected water condition.');
end
% your code after calculating the speed
end
类别
在 帮助中心 和 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!