join two different sizes of vectors to a table in matlab

To join two different sizes of vectors to a table in MATLAB, you can use the table() function along with padarray().

First, use padarray() to add NaN values to the shorter vector so that both vectors have the same length. Then, use table() to create a table with both vectors as columns. Here is an example:

main.m
% Example data
vector1 = [1; 2; 3];
vector2 = [4; 5];

% Pad the shorter vector with NaN values
if numel(vector1) > numel(vector2)
    vector2 = padarray(vector2, numel(vector1) - numel(vector2), NaN, 'post');
else
    vector1 = padarray(vector1, numel(vector2) - numel(vector1), NaN, 'post');
end

% Create the table
T = table(vector1, vector2, 'VariableNames', {'Column1', 'Column2'});
388 chars
14 lines

This will create a table T with the following content:

| Column1 | Column2 | |---------|---------| | 1 | 4 | | 2 | 5 | | 3 | NaN |

related categories

gistlibby LogSnag