Given a vector, I would like to sample without replacement elements from it repeatedly.

Given a (m x 1) vector v , I would like to ,randomly without replacement, sample s elements from it. I know I can use randsample(v,s) if I were to do this once. However, I want to do this repeatedly without using a for loop (i.e vectorization) so that it is fast.

1 件のコメント

Matt J
Matt J 2020 年 8 月 21 日
編集済み: Matt J 2020 年 8 月 21 日
However, I want to do this repeatedly without using a for loop
If you make s>1, you will receive more than one selected sample. It will give you s samples in a single call.

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

 採用された回答

Matt J
Matt J 2020 年 8 月 21 日
m=10; n=15; s=3;
V=rand(m,n); %hypothetical data
[~,ids] = sort( rand(size(V)) ,1);
ids=ids(1:s,:)+m*(0:n-1);
selection=V(ids) %selects s elements from each column of V

4 件のコメント

Cem Gormezano
Cem Gormezano 2020 年 8 月 21 日
Thank you Matt, just wondering wouldnt sort make things slower ?
Matt J
Matt J 2020 年 8 月 21 日
編集済み: Matt J 2020 年 8 月 21 日
Slower than the loop? Not on my machine,
m=10; n=1e6; s=3;
V=rand(m,n);
tic;
[~,ids] = sort( rand(size(V)) ,1);
ids=ids(1:s,:)+m*(0:n-1);
selection=V(ids);
toc; %Elapsed time is 0.306036 seconds.
tic
for i=1:n
randsample(V(:,i),s);
end
toc%Elapsed time is 4.263803 seconds.
Cem Gormezano
Cem Gormezano 2020 年 8 月 21 日
Not all heroes wear capes, thanks !!!
Matt J
Matt J 2020 年 8 月 21 日
You're quite welcome, but please Accept-click the answer if it resolved your issue.

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 8 月 21 日
編集済み: Bruno Luong 2020 年 8 月 21 日
v = 'a':'z' % your vector
n = 10; % number of "loop"
s = 3; % number of drawing without replacement
[~,ir] = maxk(rand(n,length(v)),s,2);
r = v(ir)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2020 年 8 月 21 日

コメント済み:

2020 年 8 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by