user3482383
user3482383

Reputation: 295

repmat, the size of matrix or number of use

I have a matrix for which I extract each column and do repmat function for each of them to build another matrix. Since i I have to do this for a large number of vectors(each column of my first matrix) it takes so long(relative to which I expect). If I do this for the whole matrix and then do something to build them, does it takes less time?

Consider this as an example:

A=[1 4 7;2 5 8;3 6 9]

I want to produce these

A1=[1 2 3 1 2 3 1 2 3
    1 2 3 1 2 3 1 2 3
    1 2 3 1 2 3 1 2 3]
A2=[4 5 6 4 5 6 4 5 6
    4 5 6 4 5 6 4 5 6
    4 5 6 4 5 6 4 5 6]
A3=[7 8 9 7 8 9 7 8 9
    7 8 9 7 8 9 7 8 9
    7 8 9 7 8 9 7 8 9]

Upvotes: 1

Views: 275

Answers (2)

Benoit_11
Benoit_11

Reputation: 13945

As an alternative to @thewaywewalk's answer and using kron and repmat:

clear

A=[1 4 7;2 5 8;3 6 9];

B = repmat(kron(A',ones(3,1)),1,3);


A1 = B(1:3,:)
A2 = B(4:6,:)
A3 = B(7:end,:)

Which results in the following:

A1 =

     1     2     3     1     2     3     1     2     3
     1     2     3     1     2     3     1     2     3
     1     2     3     1     2     3     1     2     3


A2 =

     4     5     6     4     5     6     4     5     6
     4     5     6     4     5     6     4     5     6
     4     5     6     4     5     6     4     5     6


A3 =

     7     8     9     7     8     9     7     8     9
     7     8     9     7     8     9     7     8     9
     7     8     9     7     8     9     7     8     9

Or as @Divakar pointed out, it would be advisable to create a single 3D array and store all your data in it (general solution):

n = 3; %// # of times you want to repeat the arrays.

A=[1 4 7;2 5 8;3 6 9];

B = repmat(kron(A',ones(n,1)),1,n);
C = zeros(n,n*size(A,2),3);

C(:,:,1) = B(1:n,:);
C(:,:,2) = B(n+1:2*n,:);
C(:,:,3) = B(2*n+1:end,:);

Upvotes: 1

Robert Seifert
Robert Seifert

Reputation: 25232

Try if this fits your needs:

A = [1 4 7;2 5 8;3 6 9];
n = 3;  %// size(A,1)

cellArrayOutput = arrayfun(@(x) repmat( A(:,x).',n,n ), 1:size(A,2), 'uni',0)

instead of different variable names, everything is stored in a cell array.

if you insist on different names, I'd recommend to use structs:

A = [1 4 7;2 5 8;3 6 9];
n = 3;

structOutput = struct;
for ii = 1:size(A,2)
    structOutput.(['A' num2str(ii)]) = repmat( A(:,ii).', n, n );
end

which gives you:

>> structOutput.A1

ans =

     1     2     3     1     2     3     1     2     3
     1     2     3     1     2     3     1     2     3
     1     2     3     1     2     3     1     2     3

and so on.

I don't expect to much performance plus, you should share your full code for further help.

Upvotes: 1

Related Questions