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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With