range = min(x):0.0001:max(x);
N = numel(range);
x = sort(x);
hit = 0;
i=1;
for j = 1:(N-1)
if range(j) <= x(i) && x(i) < range(j+1)
hit = hit + 1;
i = i+1;
if x(i) == x(i-1)
while x(i) == x(i-1) % If there are more than one of the same
hit = hit + 1; % numbers in succession, this allows x and
i = i+1; % hit to carry on incrementing.
end %while
end %if
end %if
end %for
disp(hit)
此代码比较'范围'和'x'。它会检查'x'是否在'范围'中的值之间,如果是'hit'计数器增加,那么'x'的当前值也会增加。MATLAB for for循环跳过IF语句
问题是,在x的某些随机值(据我所知他们是随机的),尽管他们应该满足'IF'语句中的不等式,'IF'语句被忽略,for循环继续因此最终的'命中'值是错误的。
'x'通常是大约一百万左右宽的一维数组。
在这个例子中,让
`x = [-2.1792 -2.1759 -2.1758 -2.1748 -2.1658 -2.1648 -2.1646 -2.1604 -2.1603 -2.1550]`
'打' 应等于 '10',而是输出 '2',因为它决定在 'J = 35' 跳过 'IF' 语句。
澄清。当 'J = 35',范围(j)= -2.1758且i = 3,这意味着X(I)= - 2.1758
我敢肯定:
range(j) <= x(i) && x(i) < range(j+1)
-2.1758 <= -2.1758 && -2.1758 < -2.1757 %**edited, meant -2.1757 not -2.1759**
是真实的。
我希望我只是在这里做一些我看不见的东西。对不起,如果这是一个格式不正确的问题,这是我第一次在这里。 提前欢呼。
-2.1758 <-2.1759 是不正确的。这是一个逻辑错误?如果值都是正数,你的代码是否工作? –
对不起,编辑到-2.1757。所以-2.1758 <-2.1757是真的。 – NathM
比较实数可能是通常的问题吗? http://stackoverflow.com/questions/8959452/matlab-double-comparison –