# How to execute the same code for a specific time?

2 views (last 30 days)

Show older comments

##### 0 Comments

### Answers (1)

Image Analyst
on 21 Jan 2023

Try a while loop. In the loop get the estimated speed and compute the error. Here is a start:

% Demonstration of how to avoid an infinite loop by setting up a failsafe.

% Set up a failsafe

maxIterations = 500; % Way more than you think it would ever need.

loopCounter = 0;

% Now loop until we obtain the required condition: a random number equals exactly 0.5.

% If that never happens, the failsafe will kick us out of the loop so we do not get an infinite loop.

refSpeed = 1000; % Initialize so we can enter the loop the first time.

estimatedSpeed = 1; % Initialize so we can enter the loop the first time.

speedDifference = abs(refSpeed - estimatedSpeed);

while speedDifference > 10 && loopCounter < maxIterations

loopCounter = loopCounter + 1;

fprintf('Iteration #%d.\n', loopCounter)

estimatedSpeed = however you get it;

speedDifference = abs(refSpeed - estimatedSpeed);

if speedDifference > 10

% Somehow change the motor speed.

end

end

% Loop is done

% Alert user if we exited normally, or if the failsafe kicked us out to avoid an infinite loop.

if loopCounter < maxIterations

% Then the loop found the condition and exited early, which means normally.

fprintf('Loop exited normally after %d iterations.\n', loopCounter);

else

% Then the loop never found the condition and exited when the number of iterations

% hit the maximum number of iterations allowed, which means abnormally.

fprintf('Loop exited abnormally after iterating the maximimum number of iterations (%d) without obtaining the exit criteria.\n', maxIterations);

end

fprintf('All done after %d iterations.\n', loopCounter)

I'd recommend you do a bilinear search to home in on the best speed rather than doing the 3* or 1/3* multiplication.

##### 2 Comments

### See Also

### Community Treasure Hunt

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

Start Hunting!