Producing 2D array from a 1D array in MATLAB

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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|

回答1:

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


回答2:

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.



回答3:

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



回答4:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!