5

Does anyone know if there is a way to produce a 2D array from a 1D array, where the rows in the 2D are generated by repeating the corresponding elements in the 1D array.

I.e.:

1D array      2D array

  |1|       |1 1 1 1 1|
  |2|       |2 2 2 2 2|
  |3|  ->   |3 3 3 3 3|
  |4|       |4 4 4 4 4|
  |5|       |5 5 5 5 5|

4 Answers 4

9

In the spirit of bonus answers, here are some of my own:

Let A = (1:5)'

  1. Using indices [faster than repmat]:

    B = A(:, ones(5,1))
    
  2. Using matrix outer product:

    B = A*ones(1,5)
    
  3. Using bsxfun() [not the best way of doing it]

    B = bsxfun(@plus, A, zeros(1,5))
    %# or
    B = bsxfun(@times, A, ones(1,5))
    
Sign up to request clarification or add additional context in comments.

1 Comment

@merv: you can read more about these "Techniques for Improving Performance" at mathworks.com/access/helpdesk/help/techdoc/matlab_prog/… @woodchips: the first example you gave is the same as the one given by gnovice. The second is not really a general repmat alternative, only a special case for this particular A..
8

You can do this using the REPMAT function:

>> A = (1:5).'

A =

     1
     2
     3
     4
     5

>> B = repmat(A,1,5)

B =

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

EDIT: BONUS ANSWER! ;)

For your example, REPMAT is the most straight-forward function to use. However, another cool function to be aware of is KRON, which you could also use as a solution in the following way:

B = kron(A,ones(1,5));

For small vectors and matrices KRON may be slightly faster, but it is quite a bit slower for larger matrices.

Comments

1

repmat(a, [1 n]), but you should also take a look at meshgrid.

Comments

0

You could try something like:

a = [1 2 3 4 5]'
l = size(a)
for i=2:5
    a(1:5, i) = a(1:5)

The loop just keeps appending columns to the end.

2 Comments

For small matrices this solution is faster, but for larger sizes repmat is a much better solution. (With a 1000x1000 matrix, repmat is 500+ times faster!)
I agree, my solution is a pretty naive on, using repmat is a much better/more elegant solution in general.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.