Search code examples
matlabmatrixvectorizationcell-array

How to get all unique values in a cell array of matrices?


I want to get all unique values in A, where A is a cell array of matrices of different shapes and sizes:

A = {[], 1, [2 3], [4 5; 6 7]};
U = [];
for ii = 1: numel(A)
    a = A{ii};
    U = [U; a(:)];
end
U = unique(U);

That returns:

U =
 1     2     3     4     5     6     7

If all elements in A where row vectors, I could use [A{:}] like:

U = unique([A{1:3}]);

That returns:

U =
 1     2     3

But in my case it throws an exception:

Error using horzcat

Dimensions of matrices being concatenated are not consistent.

So how can I avoid that for-loop?


Solution

  • You can use cellfun to reshape all elements in the cell.

    U = unique(cell2mat(cellfun(@(x)reshape(x,1,numel(x)),A, 'UniformOutput', false)));
    

    or avoiding the reshapewith

    U = unique(cell2mat(cellfun(@(x)x(:).',A, 'UniformOutput', false)));