Creating a guess and check loop
6 views (last 30 days)
Show older comments
William Arsola
on 20 Jan 2017
Commented: Geoff Hayes
on 20 Jan 2017
Hello everyone. I am wanting to create function in matlab that will do the following:
From a given rectangular cross section (inputs being height and width) I want matlab to first guess a given distance that is a fraction of the height.
After that I want matlab to execute 5 simple addition/multiplication commands. The 6th command will use data from the previous 5 steps and compile an equation. (T=X+Y, these variables found in previous 5 steps) & if the equation is true I want matlab to go on and compute a few more things. BUT if T>X+Y I want matlab to go back and select a larger fraction of the height, if T<X+Y I want matlab to go back and select a smaller fraction of h. After it selects this new value I want matlab to continue that same loop until the equation T=X+Y is satisfied.
Any help or pointers are appreciated. I would think that I put a "while loop" in there somewhere? but not sure. I am good with if and if else statements too if you think I should utilize those to make this most efficient. Thanks everyone in advance!
-Will
0 Comments
Accepted Answer
Geoff Hayes
on 20 Jan 2017
William - yes, a while loop seems reasonable. You will want to put an upper bound on the maximum number of iterations that your loop should execute so that you don't become stuck in the loop. For example,
maxIters = 10000;
atIter = 0;
while atIter <= maxIters
atIter = atIter + 1;
% etc.
end
And you will need to use if and elseif statements because of the conditions you have for T>X+Y and T<X+Y.
2 Comments
Geoff Hayes
on 20 Jan 2017
William - just add a condition to your while loop
while abs(T-CC+Cs) > eps && atIter <= maxIters
% etc.
end
Note how I've changed your first condition to be a difference that is greater than a small number, eps. Using equality or inequality (like you are doing) is only valid for integers and so it is good practice to look at the absolute difference and action on that.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!