0

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I'd go with ismember indeed. +1
The condition is always satisfied. If user_input == 256 then user_input ~= 128 and user_input ~= 64. I suspect the OP wants &.
Or, perhaps simpler, while ~any(user_input==conditional values)
ismemeber seems like the best way since I need something that will act as if it were an ||, not an &&. Thank you for your help.
@bobdude "I need something that will act as if it were an ||, not an &&"... Not according to your conditions. If you use || you're going to continue looping if your value is not equal to any of the comparison values. You've created an infinite loop since a single value can't be equal to all of them.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.