简体   繁体   English

给定值和 bin 边缘,在 MATLAB 中找到每个值的 bin

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

I have a set of values and I want to find out to which bin each of them belong in more compact, likely vectorized and most importantly faster than the one below,我有一组值,我想找出它们各自属于哪个 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

for example,例如,

values =

   28.6037   37.7998   30.8294


bins =

     0    10    20    30    40    50


binValues =

     3     4     4

Perhaps, take a look at MATLAB's discretize function introduced in R2015a .也许,看看 R2015a 中引入的 MATLAB 的discretize R2015a With this function, you can replace your loop with:使用此 function,您可以将循环替换为:

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

You can assign values on bin-edges to either the left or right bin with the IncludeEdge parameter.您可以使用IncludeEdge参数将 bin-edges 上的值分配给左侧或右侧 bin。 For example, does 10 belong to bin 1 (ie: ..., "IncludeEdge", "left" ) or bin 2 (ie: ..., "IncludeEdge", "right" ).例如, 10属于 bin 1 (即: ..., "IncludeEdge", "left" )还是 bin 2 (即: ..., "IncludeEdge", "right" )。

Finally, note that values outside of the bin range will be assigned bin value of NaN .最后,请注意,bin 范围之外的值将被分配为NaN的 bin 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM