File Exchange

Unique elements in cell array

version 1.0.0.0 (1.4 KB) by Patrick Mineault

Patrick Mineault (view profile)

unique for numeric cell arrays. If c = {[0],[1,2],[0],[8],[1,2]} returns {[0],[1,2],[8]}

Updated 08 Jun 2011

function [Au, idx, idx2] = uniquecell(A)

Same as built-in unique, but works for cell arrays where each element is a numeric array.

For A a cell array of matrices (or vectors), returns Au, which contains the unique matrices in A, idx, which contains the indices of the last appearance of each such unique matrix, and idx2, which contains th indices such that Au(idx2) == A

Example usage:

A = {[1,2,3],[0],[2,3,4],[2,3,1],[1,2,3],[0]};
[Au,idx,idx2] = uniquecell(A);

Results in:

idx = [6,5,4,3]
Au = {[0],[1,2,3],[2,3,1],[2,3,4]}
idx2 = [2,1,4,3,2,1]

Algorithm: uses cellfun to translate numeric matrices into strings then calls unique on cell array of strings and reconstructs the initial matrices.

Cite As

Patrick Mineault (2019). Unique elements in cell array (https://www.mathworks.com/matlabcentral/fileexchange/31718-unique-elements-in-cell-array), MATLAB Central File Exchange. Retrieved .

Katharina Hofer

Katharina Hofer (view profile)

Would be exactly what I need, but unfortunately it does not take matrix shape into account and thus claims that the two matrices in the example below are identical:
uniquecell([{[1 1 1; 1 1 0]},{[1 1; 1 1; 1 0]}])
which leads to only one of them in the output

I fixed the issue by adding a line at the top and modifying the second line
B = cellfun(@(x) num2str(x(:)'),A_mod,'UniformOutput',false); % replace the A in the original code for A_mod (only in this line)

There might be more efficient ways to fix this.
Also, I have not tested this extensively, so I do not know whether this might introduce issues in some cases.

Thank you for the function!

Abhinav

Valeriy

Valeriy (view profile)

Excellent function. Thank you.

Sapna S

Sapna S (view profile)

Abdul-Lateef Opebiyi

Abdul-Lateef Opebiyi (view profile)

Thanks, this function makes my calculation a lot simple

Tobi Busari

Tobi Busari (view profile)

Diego Lozano-Soldevilla

Showmin

Great work.

I Chieh Chen

I Chieh Chen (view profile)

Really nice, thanks a lot~

Kevin Bartlett

Andrey

Andrey (view profile)

Good, but limited usage only to numeric matrixes.

Jessica Lam

Jessica Lam (view profile)

Really Useful.
Thanks so much=)

MATLAB Release Compatibility
Created with R2008b
Compatible with any release
Platform Compatibility
Windows macOS Linux