0
votes

I have some data in 10 matrices. Each matrix has a different number of rows, but the same number of columns.

I want to combine all 10 matrices to one matrix row-wise, interleaved, meaning the rows in that matrix will look like:

row 1 from matrix 0
...
row 1 from matrix 9
row 2 from matrix 0
...
row 2 from matrix 9
...

Example (with 3 matrices):

Matrix 1: [1 2 3 ; 4 5 6; 7 8 9] Matrix 2: [3 2 1 ; 6 5 4] Matrix 3: [1 1 1 ; 2 2 2 ; 3 3 3] Combined matrix will be: [1 2 3 ; 3 2 1 ; 1 1 1 ; 4 5 6 ; 6 5 4 ; 2 2 2 ; 7 8 9 ; 3 3 3]

2
You'll need a combination of reshape and vertcat or concatenation using [ _ , _ ] (horizontal) and [ _ ; _ ] (vertical) - Wolfie
I'm pretty new to matlab, and thus don't have much idea of how to start. If you could post a code that does it so I can learn from it i'd appreciate it. - Raz Moshe
Provided example. - Raz Moshe
Well, the direct way would be to make all of the matrices the same size by padding with NaNs, combining, and then removing the NaN rows, but that feels like a bit of a hack. - beaker

2 Answers

1
votes

You can download the function interleave2 here https://au.mathworks.com/matlabcentral/fileexchange/45757-interleave-vectors-or-matrices

z = interleave2(a,b,c,'row')

you can see the way the function works in the source code of course

1
votes

Here's a general solution that allows you to place however many matrices you want (with matching number of columns) into the starting cell array Result:

Result = {Matrix1, Matrix2, Matrix3};
index = cellfun(@(m) {1:size(m, 1)}, Result);
[~, index] = sort([index{:}]);
Result = vertcat(Result{:});
Result = Result(index, :);

This will generate an index vector 1:m for each matrix, where m is its number of rows. By concatenating these indices and sorting them, we can get a new index that can be used to sort the rows of the vertically-concatenated set of matrices so that they are interleaved.