ChanChow
ChanChow

Reputation: 1366

How to fill a matrix using elements from another?

I have a matrix:

A = [1;2;3;4];

I would like to create another matrix B of size 20*1 from A. How can I implement that effectively? Elements can be repeated and should be picked in random order.

Upvotes: 2

Views: 208

Answers (2)

Jonas
Jonas

Reputation: 74940

For the general case, where the elements of A can take any value, you can use randsample (you can even set different probabilities for each element).

B = randsample(A(:),20);

Upvotes: 3

bla
bla

Reputation: 26069

you can use randi for that, for your example:

B = randi(4,20,1)

For the general case where A has other values and other sizes, use indexing:

B = A(randi(numel(A),20,1))

Upvotes: 4

Related Questions