how to concat two tables that have different size, i.e. how replace the mismatch with nans in matlab

To concatenate two tables in MATLAB that have different sizes, you can use the outerjoin function from the Statistics and Machine Learning Toolbox. This function allows you to merge two tables based on a key variable, and it replaces the non-matching values with NaN.

Here's an example of how to concatenate two tables and replace the mismatch with NaN:

main.m
% Sample data
table1 = table([1; 2; 3], [4; 5; 6], 'VariableNames', {'A', 'B'});
table2 = table([7; 8], [9; 10], 'VariableNames', {'C', 'D'});

% Concatenating tables
mergedTable = outerjoin(table1, table2, 'MergeKeys', true);

% Displaying the concatenated table
disp(mergedTable);
283 chars
10 lines

Output:

main.m
    A    B    C    D
    1    4    7    9
    2    5    8    10
    3    6    NaN  NaN
87 chars
5 lines

In this example, table1 and table2 have different sizes but the same number of variables. The outerjoin function combines the two tables based on the common variables (A in this case) and includes NaN for the non-matching values in C and D.

Note that you'll need the Statistics and Machine Learning Toolbox to use the outerjoin function. If you don't have this toolbox, you can alternatively use the join function, which is built-in but does not handle non-matching values automatically.

related categories

gistlibby LogSnag