Another option to do it (which I wouldn't know either) would be, for example, to make a matrix that, based on idx that creates as many ones as elements indicated by idx(1), as many twos as elements indicated by idx(2),... as many x's as elements indicated by idx(end), in this case:
idx = [2;4;3];
B = [1;1;2;2;2;2;3;3;3];
Then a loop could be made so that the different elements could be separated in the corresponding cells.
It's just an idea since, as I said, I wouldn't know how to solve it that way either.