merge two tables in matlab
5 views (last 30 days)
Show older comments
Hi, I have Table1
SampleName P1 P2 P3
A 2 3 4
B 5 7 8
C 6 8 6
and Table2:
SampleName P4 P5
A 1 3
B 2 5
D 5 7
I want to merge Table1 and Table2 in the following way:
SampleName P1 P2 P3 P4 P5
A 2 3 4 1 3
B 5 7 8 2 5
C 6 8 6 0 0
D 0 0 0 5 7
I copied some code and modify it to express my question:
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
something1 = [38;43;38;40;49];
something2 = [71;69;64;67;64];
something3 = [176;163;131;133;119];
something4 = [124; 109; 83; 75; 80];
Table1 = table(something1,something2,something3,something4,...
'RowNames',LastName)
LastName2 = {'Matt';'Brown';'Bush';'Smith'};
something5 = [38;43;38;40];
something6 = [71;69;64;67];
something7 = [176;163;131;133];
Table2 = table(something5,something6,something7,...
'RowNames',LastName2)
How to create a merged table 3 as shown in my sample.
Thanks
0 Comments
Accepted Answer
Mohammad Abouali
on 7 Apr 2015
Edited: Mohammad Abouali
on 7 Apr 2015
% Creating Table1
T1=table(['A';'B';'C'],[2;5;6],[3;7;8],[4;8;6],'VariableNames',{'SampleName','P1','P2','P3'})
T1 =
SampleName P1 P2 P3
__________ __ __ __
A 2 3 4
B 5 7 8
C 6 8 6
% Creating Table2
T2=table(['A';'B';'D'],[1;2;5],[3;5;7],'VariableNames',{'SampleName','P4','P5'})
T2 =
SampleName P4 P5
__________ __ __
A 1 3
B 2 5
D 5 7
% Joining the two tables
C=outerjoin(T1,T2,'MergeKeys',1)
C =
SampleName P1 P2 P3 P4 P5
__________ ___ ___ ___ ___ ___
A 2 3 4 1 3
B 5 7 8 2 5
C 6 8 6 NaN NaN
D NaN NaN NaN 5 7
%Replacing NaN values with zeros
for i=2:size(C,2)
mask=isnan(table2array(C(:,i)));
C(mask,i)={0};
end
C =
SampleName P1 P2 P3 P4 P5
__________ __ __ __ __ __
A 2 3 4 1 3
B 5 7 8 2 5
C 6 8 6 0 0
D 0 0 0 5 7
0 Comments
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!