Search code examples
arraysmatlabvectorcell-array

Extract blocks of numbers from array in Matlab


I have a vector and I would like to extract all the blocks from it:

x = [1 1 1 4 4 5 5 4 6 1 2 4 4 4 9 8 4 4 4 4]

so that I will get vectors or a cell containing the blocks:

[1 1 1], [4 4], [5 5], [4], [6], [1], [2], [4 4 4], [9], [8], [4 4 4 4]

Is there an efficient way to do it without using for loops? Thanks!


Solution

  • You can use accumarray with a custom anonymous function:

    y = accumarray(cumsum([true; diff(x(:))~=0]), x(:), [], @(x) {x.'}).';
    

    This gives a cell array of vectors. In your example,

    x = [1 1 1 4 4 5 5 4 6 1 2 4 4 4 9 8 4 4 4 4];
    

    the result is

    y{1} =
         1     1     1
    y{2} =
         4     4
    y{3} =
         5     5
    y{4} =
         4
    y{5} =
         6
    y{6} =
         1
    y{7} =
         2
    y{8} =
         4     4     4
    y{9} =
         9
    y{10} =
         8
    y{11} =
         4     4     4     4