0

I have a vector for which I want to replicate its elements in both row and column directions. I have found that using ones built-in function is faster that m-file functions repmat and kron. I have seen some examples for replicating a vector in one direction, however I could not find how to do it in both direction.

Consider the following example:

a = [1 2 3];

I want to create these matrices:

b = [1 1 1 
     1 1 1
     2 2 2
     2 2 2
     3 3 3
     3 3 3]; 

and

c = [1 2 3 1 2 3
     1 2 3 1 2 3];

How can I do this with ones? It there any faster way?

In my code, the vectors to be replicated are bigger and also I have to do this for many vectors in a for loop. so I am looking for a faster way.

How about if I had a matrix to be replicated? for example:

d = [1 2 3
     4 5 6];

and I want to have:

e = [1 2 3 1 2 3
     4 5 6 4 5 6
     1 2 3 1 2 3
     4 5 6 4 5 6];
shaloo shaloo
  • 213
  • 1
  • 2
  • 9
  • 1
    Your last case is straightforward `repmat(d, 2, 2)`. For `b` did you only want one row of `3`s? `c` is also a straightforward `repmat`: `c=repmat(a,2,2)` – Dan Nov 11 '14 at 10:59
  • Can you provide an example of when `ones` is faster than `repmat`? – Dan Nov 11 '14 at 11:26
  • Just a thought: maybe, in your real problem, you don't really have to replicate those matrices, but come up with a neat way around this repeated replications instead... – Nras Nov 11 '14 at 12:37

2 Answers2

1

c and e are straightforward cases for repmat. b is different, the most common suggestion is to use kron(a', ones(2,3)) but here are some alternatives: A similar function to R's rep in Matlab

According to the many answers in that link, the fastest is possibly

reshape(repmat(a, 6, 1), 3, 6)'
Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157
  • I know I can use `repmat` and `kron`, but as I said, I found that `ones` can do that faster, How can I write it with `ones` is my question – shaloo shaloo Nov 11 '14 at 11:12
  • @shalooshaloo The link I provided shows that `ones` is not necessarily the fastest solution and repmat may well be faster. – Dan Nov 11 '14 at 11:18
0

You can do it in a simple and ricorsive way:

d = [1 2 3; 4 5 6];

while (!(STOP_CONDITION_OCCURS))

d = [d d; d d];

end;

etc.

  • ...but isn't this an infinite loop that will only stop once `d` consume all your memory? – Dan Nov 14 '14 at 09:55
  • You are right, but I expected that shaloo will set its own stopping condition. I edit the answer to clarify. Thank you! – user3214821 Nov 18 '14 at 11:31