How to enable while 1 loop in matlab?
Show older comments
I am planning to make a BMI calculation in which this program will prompt the user to enter new inputs repetitively as long as both inputs are positive. In this case, my input is weight and height. I have applied
while
loop in my code. However, when I enter two positive inputs and after the BMI calculation has been performed, the process ends and exits. May I know which line did I code wrongly?
while 1
if (Weight > 0 && Height > 0)
Weight = input('Please Enter Your Weight In kg: ');
Height = input('Please Enter Your Height In m : ');
BMI = Weight/(Height^2);
if (BMI<=18.5)
disp(['Health condition: THIN. Your BMI is ', num2str(BMI)]);
elseif (BMI>=18.6) && (BMI<=24.9)
disp(['Health condition: HEALTHY. Your BMI is ', num2str(BMI)]);
elseif (BMI<=25) && (BMI<=29.9)
disp(['Health condition: OVERWEIGHT. Your BMI is ', num2str(BMI)]);
else (BMI>=30)
disp(['Health condition: OBESE. Your BMI is ', num2str(BMI)]);
end
break
end
end
5 Comments
Awais Saeed
on 28 Nov 2021
Remove the "break" from the end, it is moving you out of the while loop. For how many times you want to run the loop? Removing the break statement will make the loop run infinitly.
TEOH CHEE JIN
on 28 Nov 2021
Jan
on 28 Nov 2021
if (BMI<=18.5)
...
elseif (BMI>=18.6) && (BMI<=24.9)
This fails for a BMI = 18.55. Better:
if (BMI<=18.5)
...
elseif (BMI<=24.9)
The case BMI > 18.5 need not to be checked again, because it was excluded before.
The test conditions for the other breakpoints all have similar issue -- there are intervals between each where the breakpoints are written to one decimal but a BMI calculation could return a value between 18.5 and 18.6, etc., for which there would be no output shown.
I see looking at CDC web site that's how they define the intervals and they round to one decimal point, but code to implement the algorithm must handle all possible computed results.
One could alternatively do the calculation, round and then do the switch.
Dr. Kelsey Joy
on 29 Nov 2021
I am glad to read you removed the break based on the previous comment.
I recommend consider putting individual error checks on each of your inputs for Weight and Height variables. You can refer to this example to help with this: https://www.mathworks.com/matlabcentral/fileexchange/102674-educational-validating-user-inputs-numbers-and-strings
Accepted Answer
More Answers (0)
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!