Merge cell that has common element

3 Ansichten (letzte 30 Tage)
NA
NA am 16 Apr. 2020
Bearbeitet: NA am 17 Apr. 2020
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 Kommentare
Stephen23
Stephen23 am 17 Apr. 2020
Can each matrix only be used once in the output, or can the be used multiple times?
NA
NA am 17 Apr. 2020
Bearbeitet: NA am 17 Apr. 2020
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Tommy
Tommy am 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

Weitere Antworten (1)

Stephen23
Stephen23 am 17 Apr. 2020
Bearbeitet: Stephen23 am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by