Merge cell that has common element
4 views (last 30 days)
Show older comments
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]};
2 Comments
Stephen23
on 17 Apr 2020
Can each matrix only be used once in the output, or can the be used multiple times?
Accepted Answer
Tommy
on 17 Apr 2020
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
0 Comments
More Answers (1)
Stephen23
on 17 Apr 2020
Edited: Stephen23
on 17 Apr 2020
Simpler:
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]};
ii = 1;
while ii<=numel(A)
kk = [];
for jj = ii+1:numel(A)
if numel(intersect(A{ii}(:),A{jj}(:)))
A{ii} = [A{ii};A{jj}];
kk = [kk,jj];
end
end
A(kk) = []; % remove cells
ii = ii+1;
end
0 Comments
See Also
Categories
Find more on JSON Format in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!