簡體   English   中英

MATLAB'for'循環跳過IF語句

[英]MATLAB 'for' loop skipping IF statement

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”是否介於“ range”的值之間,如果是,則“ hit”計數器遞增,因此“ x”的當前值也遞增。

問題是,對於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**

是真的。

我希望我只是在做些看不見的愚蠢的事情。 抱歉,如果這是一個格式錯誤的問題,這是我的第一個問題。 提前加油。

后續數字x(i)可以通過此測試:

if range(j) <= x(i) && x(i) < range(j+1)

實際上不等於其鄰居:

    if x(i) == x(i-1)

它可能會無限大,因此您移至下一個j ,它超出范圍。 您的內部while需要與外部if相同的條件。 而且您可以在if COND while COND跳過if COND while COND僅執行while COND因為它的工作原理相同。

以下代碼不會更簡單,更快並且得到相同的結果嗎?

x = sort(x)
hit = sum(diff(x)==0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM