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,
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
. With this function, you can replace your loop with:
binValues = discretize(values, bin, 'IncludeEdge', 'right');
You can assign values on bin-edges to either the left or right bin with the IncludeEdge
parameter. For example, does 10
belong to bin 1
(ie: ..., "IncludeEdge", "left"
) or bin 2
(ie: ..., "IncludeEdge", "right"
).
Finally, note that values outside of the bin range will be assigned bin value of NaN
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.