Merge cell that has common element

조회 수: 2 (최근 30일)
NA
NA 2020년 4월 16일
편집: NA 2020년 4월 17일
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