Randomly choose one nonzero element in each row of matrix

1 回表示 (過去 30 日間)
Peter Uwsen
Peter Uwsen 2022 年 6 月 9 日
コメント済み: Peter Uwsen 2022 年 6 月 14 日
Hello,
I have a 3D-matrix filled with ones and zeros. For example:
ex(:,:,1) =
0 1 0 1
0 0 0 1
1 0 0 1
ex(:,:,2) =
0 1 0 0
1 1 1 1
1 0 0 1
ex(:,:,3) =
0 1 1 0
0 1 1 0
1 0 1 0
In each row I need to randomly select one nonzero element and get its index. Best would be to get a 3 x 1 x 3 matrix with the (column) indexes of the randomly chosen element for each row.
I think I know how to do it with loops, but I want to avoid them since the matrix will be quite big.
Any ideas on how to solve this with no loops?
Thank you in advance for your answers!

採用された回答

David Hill
David Hill 2022 年 6 月 9 日
Need a single loop in third dimension.
ex=randi(2,10,17,12)-1;
E=permute(ex,[2,1,3]);
[r,c]=find(E);
N=zeros(size(ex,1),1,size(ex,3));
for k=1:size(ex,3)*size(ex,1)
f=find(c==k);
try%in case some rows don't have any 1's
N(k)=r(f(randperm(length(f),1)));
end
end
  1 件のコメント
Peter Uwsen
Peter Uwsen 2022 年 6 月 14 日
Thanks a lot!! Works great :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by