Home > Mobile >  unique pair of cells where order is not important
unique pair of cells where order is not important

Time:12-24

I have a cell array of pairs of strings:

str={'A','BB','A','A'}
pairs=str(nchoosek(1:numel(str),2));

pairs =
6×2 cell array

{'A' }    {'BB'}
{'A' }    {'A' }
{'A' }    {'A' }
{'BB'}    {'A' }
{'BB'}    {'A' }
{'A' }    {'A' }

and I want to be able to have an index for the unique pairs regardless of order, in the sense that A-BB and BB-A are the same pair. the function unique only gives the unique labels A,BB.

when I try unique(cell2mat(pairs),'rows') I get an error because "Dimensions of arrays being concatenated are not consistent".

when I tried table2cell(unique(cell2table(pairs))) the order matters and I get

3×2 cell array
{'A' }    {'A' }
{'A' }    {'BB'}
{'BB'}    {'A' }

I would like to be able to find \ ismember such that only

{'A' }    {'A' }
{'A' }    {'BB'}

are unique and that the index for the A-BB contains also the BB-A case. help please?

CodePudding user response:

You could use sort(..., 2) to sort within each row of pairs and then apply unique(... 'rows') with two outputs. However, that use of sort does not work for cell arrays of char vectors. The solution is to convert to a string array:

[result, index_unique, index_repeated] = unique(sort(string(pairs), 2), 'rows');

If you need the result as a cell array of char vectors you can convert back:

result = arrayfun(@char, result, 'UniformOutput', false);
  • Related