简体   繁体   English

多条件While循环(在同一变量中带有多个条件)

[英]Multi Condition While Loop (w/ multiple conditions within same variable)

Here's the basic setup. 这是基本设置。 I am trying to create a while loop that will iterate until a set condition is below a certain tolerance. 我正在尝试创建一个while循环,该循环将迭代直到设置的条件低于某个公差为止。 However, this loop must be generalized for multiple values within the same matrix. 但是,必须针对同一矩阵内的多个值推广此循环。 An example (simplified from what I'm currently trying to accomplish): 一个例子(从我目前想完成的事情简化):

x = [3; 2]
tolerance = [0,0]
iter = 0
while x > tolerance
x = x - 1;
iter = iter + 1;
end

The issue I am facing is that the while loop will exit as soon as 1 of the values in the function is less than the tolerance. 我面临的问题是,只要函数中的值之一小于公差,while循环就会退出。 What I intend to occur is that the while loop will continue to iterate on both variables until both are below the desired tolerance. 我打算发生的是,while循环将继续对两个变量进行迭代,直到两个变量均低于所需的公差为止。 I am unable to have two separate loops because the size of the variable I will be iterating upon is not set at 2 values. 我无法进行两个单独的循环,因为要迭代的变量的大小未设置为2个值。

Any kind of help would be greatly appreciated. 任何形式的帮助将不胜感激。

Matlab has a couple of related functions, any and all that help with this kind of thing. Matlab有一些相关功能, any功能all可以提供帮助。

any , which returns true if any of the elements are truthy, will help you here: any ,如果任何元素为true ,则返回true ,它将在这里为您提供帮助:

while any(x>tolerance)
   ...
end

You can also do other tricks like 您还可以执行其他技巧,例如

while sum(x>tolerance) > 0

to achieve the same thing, but I like how semantically clear any is. 达到同样的事情,但我喜欢如何语义明确的any是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM