times - repelem matlab




Replicate matrix one row at a time (7)

Good question +1. A neat one-liner method to accomplish this is via the Kronecker tensor product, eg:

A = [1 2 3];
N = 3;
B = kron(A, ones(1, N));

Then:

B =

     1     1     1     2     2     2     3     3     3

UPDATE: @Dan has provided a very neat solution that looks to be more efficient than my kron method, so check that answer out before leaving the page :-)

UPDATE: @bcumming has also provided a nice solution that should scale very nicely when the input vector is large.

I have matrix

A = [1;2;3]

How do I replicate A four times, replicating each row four times before moving onto the next, to get

[1;1;1;1;2;2;2;2;3;3;3;3;4;4;4;4]

?


How about using kron? It's perfect for this.

kron(A,ones(4, 1))

In this particular instance, you could do something along the lines of

A = [1;2;3;4];
B = repmat(A',4,1);
B = B(:);

What this does is replicate A' to create a matrix B:

 1     2     3     4
 1     2     3     4
 1     2     3     4
 1     2     3     4

It then converts it to a single column using B(:).


Yet another possibility, which involves no arithmetical operations:

reshape(repmat(A,1,6).',[],1);

However, if you really need speed, and if the A vector size is the same in all iterations of the loop, it's best to precompute (outside the loop) an indexing vector like this

ind = reshape(repmat([1;2;3],1,6).',[],1);

and then within the loop you only need to do

A(ind)

A = [3;4;5];
duplicate_factor = 6;
A = reshape((A*(ones(duplicate_factor,1))')', [], 1)

A similar function to R's rep in Matlab

You can reproduce the syntax of the rep function in R fairly closely by first defining a function as follows:

function [result]=rep(array, count)
matrix = repmat(array, count,1);
result = matrix(:);

Then you can reproduce the desired behavior by calling with either a row or column vector:

>> rep([1 2 3],3)
ans =
 1     1     1     2     2     2     3     3     3

>> rep([1 2 3]',3)
ans =
 1     2     3     1     2     3     1     2     3

Note I have used the transpose (') operator in the second call to pass the input array as a column vector (a 3x1 matrix).

I benchmarked this on my laptop, and for a base array with 100,000 elements repeated 100 times, it was between 2 to 8 times faster than using the ceil option above, depending on whether you want the first or the second arrangement.


Matlab: duplicating each row of a matrix

This question has been asked quite a few times before, for instance here, here and here (from today) .

Some solutions:

kron(A,ones(n,1))
ans =

     1     2     3
     1     2     3
     4     5     6
     4     5     6
     7     8     9
     7     8     9

Another one:

reshape(repmat(A(:)',n,[]),[],3);

And one more:

B = A(ceil((1:size(A,1)*n)/n),:)

Take your pick!