user2272952
user2272952

Reputation: 81

MATLAB concatenate 2D matrix tiles

I have n2 equally sized (8x8) matrices which I want to tile into a single matrix like in the following diagram: diagram

I know I could concatenate them column by column and then concatenate each row, but I want to know if there's a simpler method to achieve this.

Upvotes: 0

Views: 761

Answers (3)

Eitan T
Eitan T

Reputation: 32930

There's a simpler method, you can store all your matrices in a cell array, then reshape and convert back to a matrix:

In the following example, suppose that C is your n2×1 cell array of matrices:

cell2mat(reshape(C, sqrt(numel(C)), []));

The result is a single tiled matrix A as required.

Example

a = ones(2); b = 2 * a; c = 3 * a; d = 4 * a;
C = {a, b, c, d};
A = cell2mat(reshape(C, sqrt(numel(C)), []))

The result is:

A =
     1     1     3     3
     1     1     3     3
     2     2     4     4
     2     2     4     4

Note the order of the sub-matrices: they are arranged column-wise. If you want A to be:

A =
     1     1     2     2
     1     1     2     2
     3     3     4     4
     3     3     4     4

then you'll have to pass the transposed version of C to reshape:

cell2mat(reshape(C', sqrt(numel(C)), []))

Upvotes: 3

horchler
horchler

Reputation: 18504

If you already have a for loop where you create the 8-by-8 matrices, you can do something like this:

M = 8; % Rows of each block matrix
N = 8; % Columns of each square block matrix
m = 2; % Number of blocks across
n = 2; % Number of blocks vertically
A(m*n*M,N) = 0; % Preallocate an m*n*M-by-N column of blocks
for i = 1:m*n
    a = rand(M,N);          % Create your data, just random here
    A(1+M*(i-1):M*i,:) = a; % Insert data
end
A = reshape(A,[M*m N*n]); % Reshape to obtain block matrix

This assumes that you have a single for loop iterating over all n^2 (or m*n) cases. Also, it builds up A one column of blocks at a time. Note: if you need to build it with the blocks going across the rows first, then you'll need to change the allocation of A and how the data is inserted by swapping the indices.

Upvotes: 0

Roney Michael
Roney Michael

Reputation: 3994

Yes there is!

%Assuming your matrices are A1, A2, A3 and A4:
A = zeros(size(A1)*2);
A(1:8,1:8) = A1;
A(9:16, 1:8) = A2;
A(1:8, 9:16) = A3;
A(9:16, 9:16) = A4;

Upvotes: -1

Related Questions