簡體   English   中英

給定值和 bin 邊緣,在 MATLAB 中找到每個值的 bin

[英]Given values and bin edges, find the bin of each value in MATLAB

我有一組值,我想找出它們各自屬於哪個 bin 更緊湊,可能是矢量化的,最重要的是比下面的更快,

values = rand(1,3)*50;
bins = 0:10:50;
binValues = nan(size(values));
for valueIndex = 1:length(values)
    dif = bins - values(valueIndex);
    [~,locat] = min(abs(dif));
    %to see on which side it is
    if dif(locat)>0
        locat = locat - 1;
    end
    %if its outside the bins:
    if locat==0 || locat==length(bins)
        locat=nan;
    end
    binValues(valueIndex) = locat;
end

values
bins 
binValues

例如,

values =

   28.6037   37.7998   30.8294


bins =

     0    10    20    30    40    50


binValues =

     3     4     4

也許,看看 R2015a 中引入的 MATLAB 的discretize R2015a 使用此 function,您可以將循環替換為:

binValues = discretize(values, bin, 'IncludeEdge', 'right');

您可以使用IncludeEdge參數將 bin-edges 上的值分配給左側或右側 bin。 例如, 10屬於 bin 1 (即: ..., "IncludeEdge", "left" )還是 bin 2 (即: ..., "IncludeEdge", "right" )。

最后,請注意,bin 范圍之外的值將被分配為NaN的 bin 值。

暫無
暫無

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

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