Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing 2D array from a 1D array in MATLAB

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|
like image 292
Richard Avatar asked Feb 05 '10 17:02

Richard


People also ask

How do you copy a 1D array into a 2D array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping.

Can you make an array of arrays in MATLAB?

Creating Multidimensional ArraysYou can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

Why is 2D array an array of 1D array?

A two-dimensional array stores an array of various arrays, or a list of various lists, or an array of various one-dimensional arrays. It represents multiple data items in the form of a list. It represents multiple data items in the form of a table that contains columns and rows. It has only one dimension.


2 Answers

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))
    
like image 64
Amro Avatar answered Sep 22 '22 16:09

Amro


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.

like image 34
gnovice Avatar answered Sep 20 '22 16:09

gnovice