How to use outerjoin for multiple files

3 views (last 30 days)
Ngoc Nguyen
Ngoc Nguyen on 13 May 2022
Commented: Ngoc Nguyen on 13 May 2022
Could anyone please help me to solve this problem:
I have 5 files
file1.CSV (key1,var1)
file2.CSV (key1,var2)
file3.CSV (key1,var3)
file4.CSV (key1,var4)
file5.CSV (key1,var5)
How to use outerjoin for 5 files?
Thank you very much!

Accepted Answer

Stephen23
Stephen23 on 13 May 2022
fnm = compose("file%d.csv",1:5);
tbl = readtable(fnm(1));
tbl.Properties.VariableNames = {'Key1','Var1'};
for k = 2:numel(fnm)
tmp = readtable(fnm(k));
tmp.Properties.VariableNames = {'Key1',sprintf('Var%d',k)};
tbl = outerjoin(tbl,tmp, 'MergeKeys',true);
end
display(tbl)
tbl = 8400×6 table
Key1 Var1 Var2 Var3 Var4 Var5 ______ __________ __________ __________ __________ __________ 150 NaN NaN NaN NaN 0 150.06 1.6649e+05 NaN NaN NaN 1.0888e+05 150.09 2.6486e+05 2.4469e+05 2.8286e+05 55544 2.6561e+05 151.04 3.8633e+05 NaN 2.0198e+05 2.6359e+05 2.7307e+05 151.04 NaN NaN NaN NaN 0 151.08 3.3326e+05 2.0373e+05 1.9286e+05 1.5701e+05 3.7689e+05 151.09 93946 NaN NaN NaN 56807 151.11 2.7368e+05 3.4127e+05 4.3321e+05 2.3001e+05 5.1764e+05 152.07 NaN NaN NaN NaN 0 152.11 NaN NaN NaN NaN 0 153.02 NaN NaN NaN NaN 0 153.06 1.3084e+05 NaN 52030 1.2399e+05 1.8286e+05 153.09 3.5965e+05 2.7921e+05 4.6437e+05 2.9047e+05 6.9265e+05 153.13 NaN 62476 1.422e+05 NaN 1.7483e+05 154.09 NaN NaN NaN NaN 0 155.07 96101 NaN 76217 1.4462e+05 2.4583e+05

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!