MATLAB: Duplicate each element of a vector? [close

2019-01-15 17:07发布

I'm new to MATLAB and this website as well. I tried searching for this question, but to no avail (so I apologize if this ends up being a questions which has already been asked here before). In class, we were assigned a problem with the following description: "For an n-dimensional vector X, the function should return another 2n-dimension where each element is repeated twice. For example: if a=[2 3 4 5], after using the function, a=[2 2 3 3 4 4 5 5];" It should work with a vector of ANY random size.

Your help is really appreciated! Thanks

1条回答
我命由我不由天
2楼-- · 2019-01-15 17:53

use kron:

K = kron(X,Y) returns the Kronecker tensor product of X and Y. The result is a large array formed by taking all possible products between the elements of X and those of Y. If X is m-by-n and Y is p-by-q, then kron(X,Y) is m*p-by-n*q.

In your case:

kron(a,[1 1])

will give you what you wanted

Some alternatives answers for your question:

reshape([a ; a],1,[])

reshape([a'*[1 1]]',1,[])
查看更多
登录 后发表回答