for循环不会迭代 [英] The for loop doesn't iterate

查看:111
本文介绍了for循环不会迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MATLAB中,代表循环:

  for i = [1:100]'
%'//做一些事情,如disp(i)
end

显然不是真正通过迭代实现的,而是 i 变成矩阵[1 2 3 ... 100],而loop是唯一的在这个矩阵 i 上执行一次。您可以通过打印 i 或其他跟踪信息的值来验证。只有一个通过循环。



是否有可能迫使MATLAB做真正的循环?我问的原因是,上面的方法在很多情况下都是正确的,但是当你需要运行嵌套循环的时候更加痛苦。

示例

如果你认为你得到了真正的迭代循环:

  for i =离群值
data(i)= median(data(i-100: i + 100))
end

(i)从i-100到i + 100的数据的中位数,但事实并非如此。事实上,中位数会返回您所关注的所有范围的集合中计算的单个值,并且每个数据(i)点将被替换为该单个值。

解决方案

如果您为i =(1:100)写'

 '%'#square括号也可以工作
doSomething
end

循环只执行一次,因为 -loop的在等号右边的所有上迭代(它将迭代200次,由等号右边的200个数组)。然而,在你的例子中,你有 i = [1:100] ,它的计算结果是一个行向量。因此,循环应执行100倍。

如果你遍历一个可能< c $ c>,为了安全起见,你可以写:

  for i = myArray(:)'%'#guarantee nx1,然后转置为1xn 
结束


In MATLAB the following for loop:

for i = [1:100]' 
    %'// Do something, such as disp(i)
end

isn't apparently really implemented by iteration, rather i becomes the matrix [1 2 3 ... 100] and the "loop" is only executed once on this matrix i. You can verify this by printing the value of i or other tracking information. Only a single pass is made through the loop.

Is it possible to force MATLAB to do genuine looping? The reason I ask is that the above approach is fine for many cases but much more painful when you have nested loops that need to run.

Example:
The following code won't do what you would expect if you thought you were getting actual iteration over a loop:

for i = outlier
    data(i) = median(data(i-100:i+100))
end

One would expect at each outlier index this would replace data(i) with the median of the data from i-100 to i+100, but it doesn't. In fact, the median returns a single value computed on a conglomerate of all the ranges you cared about, and every data(i) point is replaced with that single value.

解决方案

If you write

for i = (1:100)' %'# square brackets would work as well
   doSomething
end

the loop is executed only once, since a for-loop iterates over all columns of whatever is to the right of the equal sign (it would iterate 200 times with a 100-by-200 array to the right of the equal sign).

However, in your example, you have i=[1:100], which evaluates to a row vector. Thus, the loop should execute 100x.

If you iterate over an array that might be nx1 instead of 1xn, you can, for safety reasons, write:

for i = myArray(:)'  %'# guarantee nx1, then transpose to 1xn
end

这篇关于for循环不会迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆