Random numbers from array

14 ビュー (過去 30 日間)
Mohammad
Mohammad 2015 年 11 月 7 日
コメント済み: Walter Roberson 2024 年 7 月 14 日
Suppose I have the following array A=[2,1,5,6,20,55,6,9,100,1000,325,2301] which contains distinct numbers I want to select for example four elements from the array randomly and then delete them from the original array. For example if the selected numbers were 20,2,9,325 so the new array R=[20,2,9,325] and A=the remaining elements.

採用された回答

Geoff Hayes
Geoff Hayes 2015 年 11 月 7 日
編集済み: Geoff Hayes 2015 年 11 月 7 日
Mohammed - just use randperm to generate four random numbers that you can use as indices into your array. Try the following
% generate the four random indices
randIdcs = randperm(length(A),4);
% initialize R to be the four numbers of A
R = A(randIdcs);
% remove those four numbers from A
A(randIdcs) = [];
If order is important, then just sort the output of randperm
randIdcs = sort(randperm(length(A),4));
  2 件のコメント
Yasir Khan
Yasir Khan 2024 年 7 月 14 日
will these indices be unique?
Walter Roberson
Walter Roberson 2024 年 7 月 14 日
The output of randperm() will be unique values.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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