2016-03-15 56 views
4

給定範圍的一組數:確定哪些範圍內的數落入

a = 

    32225 52259 
    52260 70794 
    70795 91459 
    91460 95409 

和單個值x = 61450 - 有一種方法來確定其內範圍X落在而不使用循環來檢查每個可能性?在這種情況下的答案是2,因爲61450落在第二範圍內。

回答

9

使用

res = find(x >= a(1,:) & x < a(2,:)); 
+3

我會建議在其中一邊添加'='。 – Adiel

+0

@Adiel,感謝您的評論,我同意 – drorco

+1

@Anna如果範圍總是增加並且連續,'result = sum(x> = a(:,1));'這也適用 –

5

OK,做一個:-)。

foo = [1;round(1e5*rand(1000,1))]; 
foop = [ foo(2:end)+1;1e6]; 

x = 1e5*rand(1,1); 
tic 
for j = 1:1000 

    bardro = find(x >= foo & x <= foop); 
end 
tocdro = toc; 

tic; 
for j = 1:1000 
    barlui = sum(x >=foo); 
end 
toclui = toc; 

>> tocdro 
tocdro = 
    0.0113 
>> toclui 
toclui = 
    0.0047 

我們贏了!

相關問題