Search code examples
matlabcell-array

Convert numbers to sequence of numbers in cell-array rows


I want to convert [5,3,7] to a cell array where every row would be a range from '1:to_the_respective_number'. However this seems surprisingly hard to achieve. Can someone point out where I went wrong?

nums=[5,3,7];
cellfun(@(x) 1:x, num2cell(nums),'UniformOutput',0)

ans =
  1×3 cell array
    {1×5 double}    {1×3 double}    {1×7 double}

what I actually wanted to get is (stiched this together in the variable explorer)

{1,2,3,4,5,[],[];1,2,3,[],[],[],[];1,2,3,4,5,6,7}
ans =
  3×7 cell array
    {[1]}    {[2]}    {[3]}    {[       4]}    {[       5]}    {0×0 double}    {0×0 double}
    {[1]}    {[2]}    {[3]}    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {[1]}    {[2]}    {[3]}    {[       4]}    {[       5]}    {[       6]}    {[       7]}

Solution

  • Here are two ways to get the desired result:

    1.Using arrayfun.

    nums=[5,3,7];
    m = max(nums);
    row  = arrayfun(@(x){[num2cell(1:x) cell(1, m-x)]}, nums );
    result = vertcat(row{:});
    

    2.A vectorized solution.

    nums=[5,3,7];
    m = max(nums);  
    result = repmat(num2cell(1:m),numel(nums),1);
    result(bsxfun(@gt, 1:m , nums.'))={[]};