How can I make the program select a random element from an array. So:

A=[1 2 3 4] 

random= random element of A

I tried randsample(A,1) and randi(A) and neither worked so what can I do

2

1 Answer

Just use randi to generate a random index over the length of A. No fancy toolboxes needed:

>> A = [1 2 3 4]; >> x = A(randi(length(A),1)) x = 4 >> x = A(randi(length(A),1)) x = 3 

etc.

randi(A) does not work because the first argument of randi is the bound of the random integer. Always check the docs:

>> help randi randi Pseudorandom integers from a uniform discrete distribution. R = randi(IMAX,N) returns an N-by-N matrix containing pseudorandom integer values drawn from the discrete uniform distribution on 1:IMAX.