# Merge two Matrices without Duplicates

I have two matrices, for example:

data1 = {{"c1", "c2", "c3"}, {2, 5, 3}, {54, 2, 3}, {11, 2, 10}, {3,
5, 7}};

and

data2 = {{"c1", "c2", "c3"}, {11, 2, 10}, {3, 5, 7}, {2, 5, 3}, {54,
2, 3}, {3, 1, 4}, {5, 2, 3}};

I would like to merge these two matrices in a way that there is only one copy of the overlapping rows. This should lead to:

merged = {{"c1", "c2", "c3"}, {2, 5, 3}, {54, 2, 3}, {11, 2, 10}, {3,
5, 7}, {2, 5, 3}, {54, 2, 3}, {3, 1, 4}, {5, 2, 3}};

I'm looking for a procedure which works also for examples which don't overlapp.

-
Does Union[data1,data2] work for you or is the order of the elements important? – C. E. Feb 19 '14 at 15:02

{data1, Rest@data2} /. {{a__, b__}, {b__, c__}} :> {a, b, c}
(* {{"c1", "c2", "c3"}, {2, 5, 3}, {54, 2, 3}, {11, 2, 10},
{3, 5, 7}, {2, 5, 3}, {54, 2, 3}, {3, 1, 4}, {5, 2, 3}} *)
-
Forgetting about the header row for a moment, a___ and c___ would probably be better here, in case one of the lists is fully contained within the other. – Szabolcs Feb 19 '14 at 18:10
Thx, that's as elegant as it can get. Works perfectly! – RMMA Feb 20 '14 at 6:57

I would suggest

DeleteDuplicates@Join[data1, data2]

{{"c1", "c2", "c3"}, {2, 5, 3}, {54, 2, 3}, {11, 2, 10}, {3, 5,7}, {3, 1, 4}, {5, 2, 3}}

I am not sure what you are looking for, because you left some duplicates in the merged list

-
I think the left-over duplicates are deliberate. As I understand it the idea is to remove just the elements at the beginning of data2 which are at the end of data1, like stitching together multiple images to make a panorama. – Simon Woods Feb 19 '14 at 15:50
The problem is that I just want to get rid of the overlapp. There may exist duplicates within one of the matrices as well. – RMMA Feb 19 '14 at 15:52
@SimonWoods You should put that quote into the question. Much more clear now :) – Kuba Feb 19 '14 at 16:05