Info

This question is closed. Reopen it to edit or answer.

Merge two files with different information

1 view (last 30 days)
pink flower
pink flower on 16 Apr 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
I have two .txt files and I would like to combine the two and put them in one. My files looks like this:
file1.txt
1998 1 1 32.5
1998 1 2 37.2
1998 1 3 40.4
1998 1 5 30.8
file2.txt
1998 1 1 28.2
1998 1 2 35.2
1998 1 4 39.6
1998 1 6 33.0
So, I need an output like this:
1998 1 1 32.5 28.2
1998 1 2 37.2 35.2
1998 1 3 40.4 -
1998 1 4 - 39.6
1998 1 5 30.8 -
1998 1 6 - 33.0
or
1998 1 1 32.5 28.2
1998 1 2 37.2 35.2
1998 1 3 40.4
1998 1 4 39.6
1998 1 5 30.8
1998 1 6 33.0
or
1998 1 1 32.5 28.2
1998 1 2 37.2 35.2
1998 1 3 40.4 NaN
1998 1 4 NaN 39.6
1998 1 5 30.8 NaN
1998 1 6 NaN 33.0
After obtaining this output, remove as lines that do not contain information in the last two columns. Can anybody help me?
  1 Comment
Walter Roberson
Walter Roberson on 16 Apr 2020
I suggest you put the information into a table() object and use innerjoin()

Answers (1)

Akira Agata
Akira Agata on 21 Apr 2020
As Walter-san mentioned, the solution would be like this:
% Read .txt files
T1 = readtable('file1.txt','ReadVariableNames',false);
T2 = readtable('file2.txt','ReadVariableNames',false);
% Merge T1 and T2 using innerjoin function
Tall = innerjoin(T1,T2,'Keys',[1 2 3]);

Community Treasure Hunt

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

Start Hunting!