Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab unique cell combinations

Tags:

list

cell

matlab

I have a list as given below:

A= {[1 2], [2 1], [2 1 3],[3 4],[4 3]}

I need to simplify the matrix. For example, [3 4] and [4 3] form the same combination, only one of them is enough. Also, [1 2] and [2 1] is the same combinations, so I should be left with

newA= {[1 2],[2 1 3],[3 4]}

How do I do that?

like image 201
A Doe Avatar asked Dec 12 '25 04:12

A Doe


2 Answers

One approach is to sort the values and use unique:

A = {[1 2], [2 1], [2 1 3],[3 4],[4 3]};

tmp = cellfun(@sort, A, 'UniformOutput', false);
tmp = cellfun(@num2str, tmp, 'UniformOutput', false);
[~, idx] = unique(tmp);

newA = A(idx);

Note 1 that I've had to make a dummy array of the string equivalent of A due to unique's handling of cell arrays. unique can only work on cell arrays of strings/character vectors so we have to do a little manipulation to get the desired output.

Note 2 that cellfun is almost always slower than the explicit loop, but I've used it here for brevity.

like image 185
sco1 Avatar answered Dec 13 '25 17:12

sco1


The most efficient way is probably to sort each vector and use two nested loops as follows:

As = cellfun(@sort, A, 'UniformOutput', false); % sort each vector
remove = false(size(A)); % initiallize. Entries to be removed will be marked true
for ii = 1:numel(A)
    for jj = ii+1:numel(A)
        remove(jj) = remove(jj) || isequal(As{jj}, A{ii}); % short-circuit OR
    end
end
result = A(~remove);
like image 37
Luis Mendo Avatar answered Dec 13 '25 18:12

Luis Mendo



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!