How do I Interlace / Interleave 3 or more Matrices in MATLAB ?

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

4 Comments

Do you know which matrix is bigger?
Excellent Question, but Nope, as it stands I would not know the Matrix sizes in advance. The Columns will always be the Same lengths though, as the preceeding operation is the same 'reshape' applied to all of them.
There's always whos-ing the Matrices in question, getting the Overall Number of Columns, and inserting that into the function by hand. That would work, but this issue has kinda now peaked my curiosity. Would there be a method to have Matlab detect the Row-Lengths automatically and accordingly interleaving the Matrices?
  • C1 M4, C1 M5, C2 M1, C2 M2, C3 M2, C4 M2, C5 M2, C1 M3, C2 M3, C3 M3, C4 M3, C5 M3
Is there any logic in these or it's just have to be that way? I don't understand
Oh yeah thanks for pointing that out, screwed that Up big Time. Uno momento...
Now it's right 😌

Sign in to comment.

 Accepted 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

More Answers (1)

I think I figured it out. If my 5 Matrices are A, B, C, D, E, then
interlaced_by_column = reshape ([ A ; B ; C ; D ; E ], size(A,1), [] );
That seems to do the trick, but only if all Matrices are the same size. 🤠

Categories

Products

Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!