Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
2  
Does Union[data1,data2] work for you or is the order of the elements important? –  Pickett Feb 19 at 15:02
add comment

2 Answers

up vote 5 down vote accepted

How about this:

{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}} *)
share|improve this answer
    
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 at 18:10
    
Thx, that's as elegant as it can get. Works perfectly! –  RMMA Feb 20 at 6:57
add comment

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

share|improve this answer
    
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 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 at 15:52
    
@SimonWoods You should put that quote into the question. Much more clear now :) –  Kuba Feb 19 at 16:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.