【问题标题】:matlab while loop multiple conditionsmatlab while循环多个条件
【发布时间】:2015-12-16 16:00:42
【问题描述】:

您好,在这里使用 Matlab 进行编程,由于某种原因,我的 while 循环中不断出现错误。谁能给我一个关于如何在while循环中创建多个条件的例子?这是我的while循环,

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

我希望它是这样的,

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

感谢您的帮助!

【问题讨论】:

    标签: matlab while-loop operators conditional


    【解决方案1】:

    符号&and 逻辑运算符。您可以在 while 循环中将其用于多个条件。

    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
    

    正如烧杯所指出的,只要不是以下值之一,您要求的就是要求输入:256、128 或 64。使用 or 逻辑运算符意味着 user_input 应该是 256 , 128 和 64 同时打破循环。


    您也可以使用ismember

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

    Luis Mendo 提出的另一种方法是使用any

    conditionnal_values = [256, 128 , 64]
    while ~any(user_input==conditionnal 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 == conditionnal_value 返回一个由 1 和 0 组成的数组,具体取决于 conditionnal_values 的值是否与 user_input 匹配。然后任何查找此数组上是否至少有一个1。然后我们应用~,即not 运算符。

    【讨论】:

    • 我确实会选择ismember。 +1
    • 条件总是满足的。如果user_input == 256 然后user_input ~= 128user_input ~= 64。我怀疑 OP 想要&
    • 或者,也许更简单,while ~any(user_input==conditional values)
    • ismemeber 似乎是最好的方法,因为我需要的东西就像 ||,而不是 &&。感谢您的帮助。
    • @bobdude “我需要的东西会像 ||,而不是 &&”... 不符合您的条件。如果您使用||,如果您的值不等于任何 个比较值,您将继续循环。您创建了一个无限循环,因为单个值不能等于所有值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2022-10-14
    • 2016-04-08
    • 2016-10-08
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多