Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left Join tables in MATLAB

I tried to find something relevant but to no avail, except this post which I can't say it was helpful.

I have two tables A and B: A has dimensions 5x5 and non unique values in the LastName

LastName = {'Smith';'Johnson';'Williams';'Smith';'Williams'};
YearNow= [2010;2010;2010;2010;2010];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124; 109; 125; 117; 122];
A = table(LastName,YearNow,Height,Weight,BloodPressure);

and B has dimensions 3x2 and unique values in LastName

LastName = {'Smith';'Johnson';'Williams'};
YearBorn= [1950;1975;1965];
B = table(LastName,YearBorn);

I want to create a new column on Table A that will contain their age after I subtract for each A.YearNow the B.YearBorn, so the last column will have the form

A.Age = [60,35,45,60,45];

When I try to use [detect,pos] = ismember(A,B(:,1)); I get an error:

A and B must contain the same variables.

Any help would be appreciated.

like image 525
Jespar Avatar asked Mar 09 '23 08:03

Jespar


1 Answers

Instead of using ismember, which can be quite error-prone as you have to put things in the right order, you could also use Matlab's outerjoin instead:

A = outerjoin(A,B,'Type','Left','MergeKeys',true);
A.Age = A.YearNow - A.YearBorn;

Note that outerjoin modifies the ordering. See the official Matlab documentation for all the input arguments.

An additional advantage of outerjoin over ismember is that in case not all LastNames in table A exist in table B, you will have to pre-allocate output with ismember, and use the first output argument as well.

like image 157
jvz Avatar answered Mar 16 '23 20:03

jvz