How can I sample n elements from each column of a matrix?

2 ビュー (過去 30 日間)
Raphael
Raphael 2020 年 3 月 25 日
回答済み: Stephen23 2020 年 3 月 25 日
I have this matrix:
A =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
I want to sample n elments with replacement from each column. For instance, if n=2, I would like to get something like:
B =
2 8 10 14 20
4 8 9 15 17
I tried datasample, but it samples entire rows. Is there an efficient way to do this without using a for loop?
  1 件のコメント
KSSV
KSSV 2020 年 3 月 25 日
YOu want to select two elements from each column randomly?

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

採用された回答

David Hill
David Hill 2020 年 3 月 25 日
B=A(randi(size(A,1),2,size(A,2))+(0:size(A,2)-1)*size(A,1));
  1 件のコメント
Raphael
Raphael 2020 年 3 月 25 日
That is exactly what I wanted!
Very clever, David.
Thank you!

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

その他の回答 (2 件)

Birdman
Birdman 2020 年 3 月 25 日
Following approach can be used(using for loop):
n=2;
for i=1:size(A,2)
y(:,i)=randsample(A(:,i),n);
end
y

Stephen23
Stephen23 2020 年 3 月 25 日
>> X = sub2ind([4,5],randi(4,2,5),[1:5;1:5]);
>> B = A(X)
B =
3 8 9 13 20
3 7 10 15 20

カテゴリ

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