MATLAB Answers

Random Selection of Each Element in Vector

10 views (last 30 days)
Greetings,
I have a vector of 12 elements (a = [10 20 35 38 40 45 48 50 55 58 60 75]') and I want to randomly select one element at a time. How can I do that? Thank you very much.

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 4 Jan 2017
Adam's answer is the best use of MATLAB because it returns a vector, and it does not require the Statistics Toolbox.

Sign in to comment.

Accepted Answer

Adam
Adam on 4 Jan 2017
Edited: Adam on 4 Jan 2017
randA = a( randperm( numel(a) ) )
will give you them in a random order all at once. Then you can take them in turn if you wish.

  2 Comments

Stephen Cobeldick
Stephen Cobeldick on 4 Jan 2017
b = a(randperm(numel(a)));
for k = 1:numel(b)
b(k)
end

Sign in to comment.

More Answers (1)

KSSV
KSSV on 4 Jan 2017
Edited: KSSV on 4 Jan 2017
a = [10 20 35 38 40 45 48 50 55 58 60 75] ;
N = length(a) ;
pos = 1:N ;
idx = randsample(pos,N) ;
for i = 1:N
a(idx(i))
end

  2 Comments

Andromachi Tsouli
Andromachi Tsouli on 4 Jan 2017
Thank you so much. I see in my output when running your script that all elements are accessed, how can I modify your script to get only one element at a time as an ouput and not all of them? (sorry, totally new to matlab)

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!