How to randomly select variable from the range of numbers ?

Hi,
I have a variable
a=[1:1:100]
I would like to select from the variable a , 5 values randomnly every time. Eg 10 15 67 89 99.
Is there any way to do it in simple rather than using a for loop.
Appreciate the help

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 26일
a=[1:1:100]
out=a(randi(100,1,5))

댓글 수: 5

Wayne King
Wayne King 2012년 10월 26일
편집: Wayne King 2012년 10월 26일
@Azzi Abdelmalek
with randi() you can get repeated values so you might get elements of the vector, a, repeated by having the same index more than once.
out =
58 8 6 31 53
out =
57 25 92 83 45
I don't get what you mean
ok, but he did'nt say that a number can't be repeated
in case it can't be repeated
[~,idx]=sort(rand(1,100))
out=a(idx(1:5))
Thank you

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2012년 10월 26일
편집: Andrei Bobrov 2012년 10월 26일
a = 1:100;
ii = randperm(numel(a));
out = a(ii(1:5));
or
[ii,ii] = sort(rand(1,numel(a)));
out = a(ii(1:5));
or
out = a(randperm(numel(a),5));
Wayne King
Wayne King 2012년 10월 26일
편집: Wayne King 2012년 10월 26일
idx = randperm(length(a));
idx = idx(1:5);
a(idx)
or if you have the newest version of MATLAB
idx = randperm(length(a),5);
a(idx)

카테고리

도움말 센터File Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by