saastn
saastn

Reputation: 6025

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?

Upvotes: 0

Views: 3192

Answers (2)

Mikhail_Sam
Mikhail_Sam

Reputation: 11258

We can go this way:

A = {[], 1, [2 3], [2 0; 4 5; 6 7]};
AA = cellfun( @(x) unique(x(:)), A, 'UniformOutput' , false)
res = unique(cat(1, AA{:}))
  1. First of all create unique array for each cell - it let us avoid converting all the cells to numeric just only unique values.
  2. Lets convert cell array to one numeric array - cat(1, AA{:}) .
  3. Find unique values through this resulting array.

Upvotes: 3

Nemesis
Nemesis

Reputation: 2334

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)));

Upvotes: 3

Related Questions