Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate entries in a cell array (when those entries are 2x2 matrices) (Matlab)

Tags:

matlab

Is there a nice function that will remove duplicate entries in a cell array?

Some googling threw up the function 'unique', but it appears that only works if all the entries of the array are strings. Mine are 2x2 matrices.

Thanks

like image 202
Matt Lab Avatar asked Dec 30 '25 02:12

Matt Lab


1 Answers

I've used a combination of CELLFUN, CELL2MAT and UNIQUE. The idea is to convert each matrix to a vector, convert those cell array to a matrix and apply unique, The result you can convert back to cell array with NUM2CELL.

x = {[1 2; 3 4], [1 2; 3 4], [5 6; 7 8], [1 2; 3 4], [5 6; 7 8]}';
x1 = cellfun(@(y)y(:)', x, 'UniformOutput',0);
x2 = cell2mat(x1);
x3 = unique(x2,'rows');
x4 = num2cell(x3,2);
x5 = cellfun(@(y) reshape(y,2,2), x4, 'UniformOutput',0);

Probably it can be done with less steps.

It's important to remember that this code will work only if all the cell array elements have the same size.

You can check for this condition with

assert(size(unique(cell2mat(cellfun(@size,x,'UniformOutput',0))),1) == 1,...
       'Cell elements have different size')
like image 57
yuk Avatar answered Dec 31 '25 18:12

yuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!