MATLAB: Merge cell that has common element

merge cell that has common element

I have
A ={[1,2; 1,3; 2,4; 3,4; 2,5],[72,73],[5,6; 6,7],[36,39],[71,80;72,80],[27,70;28,71],[39,51],[21,29]};
I want to merge each cell that have common element.
for example:
[1,2; 1,3; 2,4; 3,4; 2,5] and [5,6; 6,7] have 5 in common ---> [1,2; 1,3; 2,4; 3,4; 2,5; 5,6; 6,7]
[71,80;72,80] and [27,70;28,71] have 71 in common ---> [71,80; 72,80; 27,70;28,71]
[71,80; 72,80; 27,70;28,71] and [72,73] have 72 in common ---> [71,80; 72,80; 27,70;28,71;72,73]
[36,39] and [39,51] ---> [36,39;39,51]
[21,29] does not have any common element to others ---> [21,29]
result should be
A_new ={[1,2; 1,3; 2,4; 3,4; 2,5; 5,6; 6,7],[71,80; 72,80; 27,70;28,71;72,73] ,[36,39;39,51],[21,29]};

Best Answer

I'm not sure if this is the best way to do it, but I believe it will work.
It starts by setting A_new to A. It then loops through each pair of cells in A_new, and if it finds a pair of cells which share a common element, the two cells are concatenated and put in place of one of the cells. The other cell is removed from A_new. It then restarts at the beginning, again looping through pairs of cells. This continues until no two pairs of cells share any elements.
A ={[1,2; 1,3; 2,4; 3,4; 2,5],[72,73],[5,6; 6,7],[36,39],[71,80;72,80],[27,70;28,71],[39,51],[21,29]};
A_new = A;
done = false;
while ~done
next = false;
for i=1:numel(A_new)
for j=i+1:numel(A_new)
if any(any(ismember(A_new{i},A_new{j})))
A_new{i} = [A_new{i};A_new{j}];
A_new = A_new(1:end ~= j);
next = true;
break
end
end
if next
continue
end
if i == numel(A_new)
done = true;
end
end
end