how to use horzcat on two different sizes of tables in matlab

In MATLAB, the horzcat function is used to horizontally concatenate tables. However, for tables with different sizes, you need to convert them into the same number of rows before concatenating.

Here's an example of how you can use horzcat on two tables of different sizes:

main.m
% Create two example tables
t1 = table([1; 2], {'A'; 'B'}, 'VariableNames', {'ID', 'Name'});
t2 = table([3; 4; 5], {'C'; 'D'; 'E'}, 'VariableNames', {'ID', 'Name'});

% Determine the maximum number of rows between the two tables
maxRows = max(size(t1, 1), size(t2, 1));

% Resize the tables to have the maximum number of rows
t1 = [t1; repmat(table(NaN, {''}, 'VariableNames', {'ID', 'Name'}), maxRows - size(t1, 1), 1)];
t2 = [t2; repmat(table(NaN, {''}, 'VariableNames', {'ID', 'Name'}), maxRows - size(t2, 1), 1)];

% Concatenate the tables horizontally
result = horzcat(t1, t2);
583 chars
14 lines

In this example, we first create two example tables t1 and t2 with different sizes. Then, we determine the maximum number of rows between the two tables using max. We resize both tables to have the maximum number of rows by appending NaN values using repmat. Finally, we use horzcat to horizontally concatenate the resized tables t1 and t2 into the result table.

Note that we need to use repmat to ensure both tables have the same number of rows before using horzcat.

related categories

gistlibby LogSnag