Derek
Derek

Reputation: 657

Union of two tables in MATLAB, only taking rows in one table

Suppose I have two MATLAB tables:

>> x = table({'a' 'b' 'c' 'd'}', (1:4)', 'VariableNames', {'theKey' 'theValue'})
x = 
    theKey    theValue
    ______    ________
    'a'       1       
    'b'       2       
    'c'       3       
    'd'       4       
>> y = table({'b' 'c'}', [998 999]', 'VariableNames', {'theKey' 'theValue'})
y = 
    theKey    theValue
    ______    ________
    'b'       998      
    'c'       999   

Is there a procedure (some type/combination of union/join/outerjoin maybe) which returns me the union of the two tables, but only keeps the rows from the 2nd table if there is duplication according to a key I choose (theKey)? For example, I'm looking to have this output:

    theKey    theValue
    ______    ________
    'a'       1       
    'b'       998       
    'c'       999       
    'd'       4       

Thanks!

Upvotes: 1

Views: 278

Answers (1)

zglin
zglin

Reputation: 2919

If I understand your question correctly, you're looking at unioning using outerjoin in matlab. I don't think there's a way just to do this with joins, but you may have to play some games with indexing.

>> b=outerjoin(x,y,'Type','left','MergeKeys',true,'LeftKeys',{'theKey'},'RightKeys',{'theKey'})

ans = 

    theKey    theValue_x    theValue_y
    ______    __________    __________

    'a'       1             NaN       
    'b'       2             998       
    'c'       3             999       
    'd'       4             NaN       

>> b.(2)(~isnan(b.(3)))=b.(3)(~isnan(b.(3)))

    theKey    theValue_x    theValue_y
    ______    __________    __________

    'a'       1             NaN       
    'b'       998           998       
    'c'       999           999       
    'd'       4             NaN   

>> b.(3)=[]

    theKey    theValue_x
    ______    __________

    'a'         1       
    'b'       998       
    'c'       999       
    'd'         4       

Upvotes: 1

Related Questions