首页 > 解决方案 > 分箱 1:9 -> 等号元胞数组的分箱

问题描述

以下简单问题:我想将一个向量放入一个大小相等的单元格数组groupsbins

我在解决问题时遇到了麻烦,我有一种强烈的感觉可能是单线,这是我已经走了多远:

nums=1:9; %numbers to bin
categories=discretize(nums,3); %put nums in 3 equal groups
groups=mat2cell(x); % should return: {1:3,4:6,7:9}

我错过了什么?

该解决方案应该适用于任何包含数字的一维向量,尽可能将其分箱到相同大小的箱中(任何解决方案都有效);输出应该是各个 bin 的单元格数组。

标签: matlabbinbinning

解决方案


您可以使用reshapenum2cell

result = num2cell(reshape(1:9,3,[]),1);

如果数组大小不能被您可以使用的箱数整除,histcounts并且mat2cell

nbins = 3;
a= [2 3 1 8 7 6 9 8 1];
result = mat2cell(a,1,histcounts(1:numel(a),nbins));

推荐阅读