Getting 2D array from 1D array in MATLAB

Does anyone know if there is a way to create a 2D array from a 1D array, where rows in 2D are generated by repeating the corresponding elements in a 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|
+5
source share
4 answers

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

Let A = (1:5)'

  • Using indexes [faster than repmat]:

    B = A(:, ones(5,1))
    
  • Using an external matrix product:

    B = A*ones(1,5)
    
  • Using bsxfun () [not the best way to do this]

    B = bsxfun(@plus, A, zeros(1,5))
    %# or
    B = bsxfun(@times, A, ones(1,5))
    
+9
source

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 !;)

REPMAT - . , , KRON, :

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

KRON , .

+8

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

+1
source

You can 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 simply adds columns to the end.

0
source

All Articles