MATLAB: How tonterlace / Interleave 3 or more Matrices in MATLAB

interlaceinterleaveinterweaveMATLABmatrix combination

Let's say I've 5 Matrices, all with the same Number of Rows.
How do I interlace the Columns of these Matrices,
so that Column1 of Matrix1 is followed by Column1 of Matrix2, followed by C(olumn)1 of M(atrix)3, C1 M4, C1 M5,
C2 M1, C2 M2, C2 M3, C2 M4, C2 M5,
C3 M1, C3 M2, C3 M3, C3 M4, C3 M5,
C4 M1, C4 M2, C4 M3, C4 M4, C4 M5,
C5 M1, C5 M2, C5 M3, C5 M4, C5 M5,
and so on, and so forth.
Is there a Solution which works with Matrices with differing Numbers of Columns? If one Matrix has 10 more Columns than all the others, they're just tacked onto the end of the resulting, interlaced, Matrix, for example. Or If two Matrices have 10 more Elements than the others, their Elements are alternatingly interlaced at the end.
Or do I have to make sure my Matrices have the same Number of Columns?
Thank you kindly in advance,
Tim

Best Answer

See if this works
ar = cellfun(@(x)size(x,2),data); % number of columns in each matrix
mm = size(data{1},1); % number of rows (the same for each matrix)
nn = max(ar); % max number of columns
D = zeros(mm,sum(ar)); % preallocation of BIG MATRIX
k = 1; % counter of column in BIG MATRIX
for j = 1:nn
for i = 1:numel(data)-1
if j <= ar(i) % if column exists
D(:,k) = data{i}(:,j); % fill BIG MATRIX
k = k + 1;
end
end
end