Transforming matrices in a sophisticated way

[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));
end
allC = repmat(tmpMat,1)

 Accepted 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);

1 Comment

Dear Roger, thank you for your great help! It perfectly works. Thank you, Roger, Azzi, and all. My test code is below.
% test code
a1 = [1 2 0 ; 4 3 4];
a2 = [5 6 0 ; 7 8 0];
a3 = [9 10 4; 11 0 12];
allR = [a1 a2 a3]
allC = [a1 ; a2; a3]
[p, q] = size(a1);
n = 3;
clear allC;
allC = reshape(permute(reshape(allR,p,q,n),[1,3,2]),p*n,q);
allC
clear allR;
allR = reshape(permute(reshape(allC,p,n,q),[1,3,2]),p,q*n);
allR

Sign in to comment.

More Answers (1)

It's better to put your matrics inside a cell array, instead of creating a new variabl for each matrix
a{1} = [1 2 0 ; 4 3 4];
a{2} = [5 6 0 ; 7 8 0];
a{3} = [9 10 4; 11 0 12]
allR=cat(2,a{:})
allC=cat(1,a{:})

1 Comment

Dear Azzi, Thank you for your great suggestion! Using a cell array is a brilliant idea (I'm new to matlab).
The solution, which I am searching, is transforming matrices "form allR to allC" and "from allC to allR". Do you and others have any suggestions? Many thanks. Koiti

Sign in to comment.

Categories

Products

Community Treasure Hunt

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

Start Hunting!