Search code examples
matlabvectorcell

How to unique elements of each cell vector?


Suppose I have ten cell vectors, c{1},c{2},...,c{10}, if I want to extract the unique elements of each cell vector at the same time (in a vectorized manner), how can I do it? I tried to use unique(c), but it did not work.


Solution

  • If you want to have unique elements of each cell then you have to apply unique on each cell, like unique(C{1}), unique(C{2}) etc. This can be achieved by using cellfun.

    uniqueCellArray=cellfun(@unique,yourCellArray,'UniformOutput',false);
    

    If your cell array contains a matrix then you may want to use the option 'rows'. If you don't want to sort the outpur of unique, you may want to use the option 'stable'. You can modify the above statement as follows:

    uniqueTestCell=cellfun(@(x) (unique(x,'rows','stable')),testCell,'UniformOutput',false);