MATLAB: Merging table rows, keep all columns

join tablesMATLABmerge tables

I'm trying to combine data from multiple tables into one. (data files attached). Seems like a simple join(), or outerjoin(), but every path has run into issues.
Specifically what I want to do:
  1. Add rows from table 2 to table 1.
  2. Keep all rows in both tables (append rows)
  3. Where column names match, use that column
  4. Where columns are new, add column to table width
  5. Keep column names (outer join is renaming based on source table)
  6. Some table values are empty and should combine as empty values in existing and/or new columns as needed.
Tried so far:
  1. Join – Fails do to some empty values
  2. Join w/Replaced nan – fails do to some other key value error
  3. outerjoin() w/multiple configuration options – all failed.
  4. innerjoin90 – does not seem like what I want (throwing out data).
When done combining the attached tables there should be slight more columns than the first table, and rows should be the sum of rows in both tables.
This should be a common issue so assuming I am missing some simple solution…?
Using Matlab 2016b

Best Answer

  • % Read in the data
    files = {'RESULTS_SAMP1.CSV', 'RESULTS_SAMP2.CSV'}; %Full paths are always better
    T1 = readtable(files{1},'Delimiter',',');
    T2 = readtable(files{2},'Delimiter',',');
    % Simulate column-mismatch
    T1 = removevars(T1,'SpecimenType'); % remove col 3
    T2 = removevars(T2,'Test'); % remove col 5
    % Vertically concatenate tables
    T3 = outerjoin(T1,T2,'MergeKeys', true)