MATLAB: Combining several asymmetric matrices to fit each other

array manipulationmatrix manipulation

There are matrices in an array going on and on (there can be zeros, or no zeros filling lower right elements, all elements differ):
1 1 1 1 1
1 1 1 1
1 1 1
1 1
1
8 2 2 2 2
8 2 2 2
8 2 2
8 2
8
3 3 3 3 3
3 3 3 3
3 3 3
3 3
3
6 4 4 4 4
6 4 4 4
6 4 4
6 4
6
How to stack each other matrice onto the other half to create full sizes ones, like:
1 1 1 1 1 8
1 1 1 1 8 2
1 1 1 8 2 2
1 1 8 2 2 2
1 8 2 2 2 2
3 3 3 3 3 6
3 3 3 3 6 4
3 3 3 6 4 4
3 3 6 4 4 4
3 6 4 4 4 4
And on.
A solution to flip one over the other may also work.

Best Answer

Do this for each pair of matrices A and B:
>> A = [-2,6,2,7,1;4,-5,2,3,NaN;6,1,3,NaN,NaN;2,2,NaN,NaN,NaN;4,NaN,NaN,NaN,NaN]
A =
-2 6 2 7 1
4 -5 2 3 NaN
6 1 3 NaN NaN
2 2 NaN NaN NaN
4 NaN NaN NaN NaN
>> B = [9,2,-1,6,4;5,-3,5,8,NaN;2,2,6,NaN,NaN;1,3,NaN,NaN,NaN;7,NaN,NaN,NaN,NaN]
B =
9 2 -1 6 4
5 -3 5 8 NaN
2 2 6 NaN NaN
1 3 NaN NaN NaN
7 NaN NaN NaN NaN
>> N = size(A,2);
>> X = flipud(tril(flipud(reshape(1:N*N+N,N,N+1))));
>> Y = nonzeros(sort(X.',2));
>> Z = nan(N,N+1);
>> Z(X~=0) = A(X~=0);
>> Z(X==0) = B(Y)
Z =
-2 6 2 7 1 7
4 -5 2 3 1 3
6 1 3 2 2 6
2 2 5 -3 5 8
4 9 2 -1 6 4
Note that X and Y can be calculated before the loop, assuming that N is the same for all matrices, so actually the only code you need to repeat is that for generating Z.
Note that this method does NOT rely on your data being free of NaNs, and it does not change the original data!