Merge cell that has common element

9 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2020-4-17
Can each matrix only be used once in the output, or can the be used multiple times?
NA
NA 2020-4-17
编辑:NA 2020-4-17
Should be used one time.
If [1,2; 1,3; 2,4; 3,4; 2,5] and [5,6; 6,7] are merged to [1,2; 1,3; 2,4; 3,4; 2,5; 5,6; 6,7] I only want to keep [1,2; 1,3; 2,4; 3,4; 2,5; 5,6; 6,7] and remove the [1,2; 1,3; 2,4; 3,4; 2,5] and [5,6; 6,7].
And compare [1,2; 1,3; 2,4; 3,4; 2,5; 5,6; 6,7] with others.
but for [21,29] as it dose not merge to others, I want to keep it.

请先登录,再进行评论。

采纳的回答

Tommy
Tommy 2020-4-17
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

更多回答(1 个)

Stephen23
Stephen23 2020-4-17
编辑:Stephen23 2020-4-17
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by