Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenation of N^2 3x3 matrixes into a 3Nx3N matrix

Tags:

matrix

matlab

I have N^2 matrixes. Each one is a 3x3 matrix. One way to concatenation them to a 3Nx3N matrix is to write A(:,:,i)= # 3x3 matrix i=1:N^2

matrix

B=[A11 A12 ..A1N;A21 ...A2N;...] But When N is large is a tedious work. What do you offer?

like image 288
Abolfazl Avatar asked Dec 17 '22 17:12

Abolfazl


2 Answers

Here's a really fast one-liner that only uses RESHAPE and PERMUTE:

B = reshape(permute(reshape(A,3,3*N,N),[2 1 3]),3*N,3*N).';

And a test:

>> N=2;
>> A = rand(3,3,N^2)
A(:,:,1) =
    0.5909    0.6571    0.8082
    0.7118    0.6090    0.7183
    0.4694    0.9588    0.5582
A(:,:,2) =
    0.1791    0.6844    0.6286
    0.4164    0.4140    0.5833
    0.1380    0.1099    0.8970
A(:,:,3) =
    0.2232    0.2355    0.1214
    0.1782    0.6873    0.3394
    0.5645    0.4745    0.9763
A(:,:,4) =
    0.5334    0.7559    0.9984
    0.8454    0.7618    0.1065
    0.0549    0.5029    0.3226

>> B = reshape(permute(reshape(A,3,3*N,N),[2 1 3]),3*N,3*N).'
B =
    0.5909    0.6571    0.8082    0.1791    0.6844    0.6286
    0.7118    0.6090    0.7183    0.4164    0.4140    0.5833
    0.4694    0.9588    0.5582    0.1380    0.1099    0.8970
    0.2232    0.2355    0.1214    0.5334    0.7559    0.9984
    0.1782    0.6873    0.3394    0.8454    0.7618    0.1065
    0.5645    0.4745    0.9763    0.0549    0.5029    0.3226
like image 181
gnovice Avatar answered Feb 03 '23 13:02

gnovice


Try the following code:

N = 4;
A = rand(3,3,N^2);                     %# 3-by-3-by-N^2

c1 = squeeze( num2cell(A,[1 2]) );
c2 = cell(N,1);
for i=0:N-1
    c2{i+1} = cat(2, c1{i*N+1:(i+1)*N});
end

B = cat(1, c2{:});                     %# 3N-by-3N
like image 26
Amro Avatar answered Feb 03 '23 12:02

Amro