Nick
Nick

Reputation: 1116

Matlab: repeat and concatenate rows and cols into new array

I have two 4-by-4 arrays:

a1 = [ 1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16 ]
a2 = [ 17 18 19 20; 21 22 23 24; 25 26 27 28; 29 30 31 32 ]

I need to create 16-by-8 array C:

1   2   3   4   17  18  19  20
1   2   3   4   21  22  23  24
1   2   3   4   25  26  27  28
1   2   3   4   29  30  31  32
5   6   7   8   17  18  19  20
5   6   7   8   21  22  23  24
5   6   7   8   25  26  27  28
5   6   7   8   29  30  31  32
9   10  11  12  17  18  19  20
9   10  11  12  21  22  23  24
9   10  11  12  25  26  27  28
9   10  11  12  29  30  31  32
13  14  15  16  17  18  19  20
13  14  15  16  21  22  23  24
13  14  15  16  25  26  27  28
13  14  15  16  29  30  31  32

The left half (from 1st to 4th column) of the result array C should repeat 4 times i-th row of the array a1, the right half (from 5th to 8th column) should repeat 4 times the array a2.

Below is my code.

p=4
n=4

for i=1:n
    b=n*i;
    a=n*(i-1)+1;
for j=1:p
    for k=a:b
        C(k,j)=a1(i,j);
    end;
end;
end;

for i=1:n
    b=n*i;
    a=n*(i-1)+1;
for j=p+1:2*p
    l=1;
    for k=a:b
        C(k,j)=a2(l,j-p);
        l=l+1;
    end;
end;
end;
C;
size_C=size(C)

Question. Is it possible to create result array C without for-loop? Which functions can I use?

Upvotes: 3

Views: 102

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112759

You can use ndgrid to generate the row indices and then concatenate:

[ii, jj] = ndgrid(1:size(a2,1), 1:size(a1,1));
C = [a1(jj,:) a2(ii,:)];

Upvotes: 2

Divakar
Divakar

Reputation: 221684

With focus on performance, here's one using reshape and repmat -

% Store sizes
M = size(a1,1);
N = size(a2,1);

% Get the replicated version for a1 and a2 separately
parte1 = reshape(repmat(reshape(a1,1,M,[]),[N,1,1]),M*N,[])
parte2 = repmat(a2,[M,1]);

% Do columnar concatenatation for final output
out = [parte1 parte2]

Sample run on a generic case -

a1 = % 3 x 4 array
     5     2     6     9
     7     4     7     6
     9     8     6     1
a2 = % 2 x 5 array
     7     7     1     9     2
     6     8     8     7     9
out =
     5     2     6     9     7     7     1     9     2
     5     2     6     9     6     8     8     7     9
     7     4     7     6     7     7     1     9     2
     7     4     7     6     6     8     8     7     9
     9     8     6     1     7     7     1     9     2
     9     8     6     1     6     8     8     7     9

Upvotes: 2

NLindros
NLindros

Reputation: 1693

Yes it's possible. One way of doing it is by using kron and repmat

C = [ kron(a1, ones(4,1)) repmat(a2, 4, 1)]

Perhaps the 4 should be derived from the size of one of the matrixes

Upvotes: 5

Related Questions