Search code examples
matlabwhile-loopoperatorsconditional-statements

matlab while loop multiple conditions


Hi programming in Matlab here, and for some reason I keep getting errors in my while loop. Can anyone give me an example on how to make multiple conditions in a while loop? Here is my while loop,

while (user_input ~= 256);%try catch does not work very well for this
 prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). ';
 user_input = input(prompt);
end

I would like it to be something like ,

while (user_input ~= 256 || user_input ~= 128 || user_input ~= 64)

Thank you for your help!


Solution

  • The symbol & is the and logical operator. You can use it for multiple conditions in your while loop.

    while (user_input ~= 256 & user_input ~= 128 & user_input ~= 64)
        prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). ';
        user_input = input(prompt);
    end
    

    As beaker pointed out, what you ask is to ask for input as long as it is not one of the following values : 256, 128 or 64. Using the or logical operator would mean that user_input should be 256, 128 and 64 at the same time to break the loop.


    You can also use ismember.

    conditional_values = [256, 128 , 64]
    while ~ismember(user_input, conditional_values)
        prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). ';
        user_input = input(prompt);
    end
    

    An other way to go, proposed by Luis Mendo, is to use any

    conditional_values = [256, 128 , 64]
    while ~any(user_input==conditional values)
        prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). ';
        user_input = input(prompt);
    end
    

    user_input == conditional_value returns an array composed of 1s and 0s depending on if values of conditional_values match with user_input. Then any finds if there is at least one 1 on this array. Then we apply ~ which is the not operator.