How to randomly select variable from the range of numbers ?

3 ビュー (過去 30 日間)
Karthik KJ
Karthik KJ 2012 年 10 月 26 日
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 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 26 日
編集済み: Azzi Abdelmalek 2012 年 10 月 26 日
in case it can't be repeated
[~,idx]=sort(rand(1,100))
out=a(idx(1:5))
Karthik KJ
Karthik KJ 2012 年 10 月 26 日
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)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by