Search code examples
matlabbinbinning

Binning 1:9 -> bin of equal number cell array


following simple problem: I want to put a vector into a cell array groups of equal sized bins.

I have troubles solving, and I have a strong feeling could be a one-liner, here's how far I've gotten:

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}

what am I missing?

The solution should work for any 1D vector containing numbers, bin it into as-equal-sized-bins as possible (any solution works); the output should be a cell array of the respective bins.


Solution

  • You can use reshape and num2cell:

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

    If the array size isn't divisible by the number of bins you can use histcounts and mat2cell:

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