Search code examples
matlabvectoruniquecell

MATLAB: an efficient function that can group the unique numbers from a Vector


I'm looking for an efficient MATLAB function which is able to transform a vector to a cell with group of unique numbers

e.g

from

a=[1 1 5 5 5 2 1 1 1 2 2 6 6 6 8 8 8 8] 

to

a={[1 1] [5 5 5] [2] [1 1 1] [2 2] [6 6 6] [8 8 8 8]} 

My previous approach was to locate the changing points before running within a loop:

e.g.

change_pts = a-[0,a(1:length(a)-1)];
for i=find(ans~=0)
   % codes here
end

But it's obviously not an optimised solution.

Thank you


Solution

  • You can create a vectorized solution using the functions diff and mat2cell like so:

    a = mat2cell(a, 1, diff([0 find([(diff(a) ~= 0) 1])]));
    

    This works by first locating where the values change and marking the ends of sequences of equal numbers with a 1. It then finds the indices of all the ones and computes the spans between these indices (i.e. the counts for each sequence of equal numbers). These counts are then used by mat2cell to break the vector up into a cell array.