MATLAB: Transforming matrices in a sophisticated way

MATLABmatrix conversion

[My problem]
You have three regular matrices (a1, a2, and a3), and two matrices (allR and allC), which combine the three regular matrices.
% code

a1 = [1 2 ; 3 4];
a2 = [5 6 ; 7 8];
a3 = [9 10; 11 12];
allR = [a1 a2 a3];
allC = [a1 ; a2; a3];
I need matrix transformations "from allR to allC" and "from allC to allR" in my simulation. Unfortunately, the number of regular matrices a* (a1, a2, ….., an) is not previously determined.
Is there a sophisticated way of transformations "from allR to allC" and "from allC to allR" quickly? (transpose(allR) and transpose(allC) are not appropriate solutions to my problem.) My (ugly) solution is below.
[My (ugly) solution (from allR to allC, and vice versa)]
Transformation from allR to allC:
% code
clear allC
allR = [a1 a2 a3]
[m, n] = size(allR);
maxItr = n/m;
tmpMat = allR.';
% From allR to allC
for i = 1:maxItr
tmpMat( (m*(i-1)+1):(m*i) , :) = allR(:, (m*(i-1)+1):(m*i));
allC = repmat(tmpMat,1)

Best Answer

  • If a1, a2, a3, ..., an are each p-by-q in size
    allC = reshape(permute(reshape(allR,p,q,n),[1,3,2]),p*n,q);
    allR = reshape(permute(reshape(allC,p,n,q),[1,3,2]),p,q*n);