MATLAB: How to tell the user to re-input their prompt, if their prompt does not satisfy a condition

chemical engineeringif statementloop

Hi, I am very new to MatLab so forgive me if this is an easy question.
I am writing code to initialise the volume in a reactor vessel, and at the start of the code, there is a user input which tells the user to enter the volume of the vessel. Further on, the code works out the liquid volume in the vessel using a user-specified initial amount of moles of each component.
My problem is that if the user inputs a Vessel Volume which is less than the initial volume calculated from the initial moles, there is a negative vapour space because obviously the vessel is overfilled.
My question, therefore, is there an IF function I can use, which would ask the user to re-input their initial vessel volume input, in order that the Vessel Volume > Initial Volume? A sort of loop I imagine, or perhaps a way so that the code automatically adjusts the vessel volume appropriately.
Any help on the matter is greatly appreciated. Thanks!

Best Answer

  • It is a bad practice to call input without the s option, because it will evaluate any arbitrary code, and also will produce unhelpful error messages if the user inputs a string (quite likely). A much safer and more robust solution is to always call input will its 's' option, and convert the numeric value using str2double:
    prv = 10;
    out = NaN;
    while isnan(out) || out<prv
    out = str2double(input('Enter the vessel volume: ','s'));