MATLAB: Concatenate arrays of different length into a matrix

concatenate horzcat

Assume I have two arrays (time-series) of the form:
A = [NaN, 2, 3, 4, 5, 6, 7, NaN]
B = [5, NaN, 6, 7, NaN, 8, 9, 10, 11, 12]
Since two arrays of different length can not be horzcat (obviously), how can I combine them as to obtain a 8×2 matrix where available data match. I have long time-series, so this is just an example, but it points out how crucial it is to have matching observations. Ideally, the output should be:
C = [NaN, 2, 3, 4, 5, 6, 7, NaN; 5, NaN, 6, 7, NaN, 8, 9, 10]
Thanks
Stefano

Best Answer

Truncate to shortest length using indexing:
>> N = min(numel(A),numel(B));
>> [A(1:N);B(1:N)]
ans =
NaN 2 3 4 5 6 7 NaN
5 NaN 6 7 NaN 8 9 10
Pad to longest length using padcat:
>> padcat(A,B)
ans =
NaN 2 3 4 5 6 7 NaN NaN NaN
5 NaN 6 7 NaN 8 9 10 11 12