MATLAB Answers

Create a single for loop for multiple conditions

98 views (last 30 days)
DIP on 31 Jan 2018
Answered: A. Sawas on 1 Feb 2018
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


Show 5 older comments
RobF on 31 Jan 2018
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 on 1 Feb 2018
Moritz, RobF, the speeds are different, how can I input multiple conditions for speed and use only one for loop ?
Walter Roberson
Walter Roberson on 1 Feb 2018
"the speeds are different"
Not in the code you posted.

Sign in to comment.

Answers (1)

A. Sawas
A. Sawas on 1 Feb 2018
I suggest you use switch statement like this:
% 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
warning('Unexpected water condition.');
% your code after calculating the speed


Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!