Randomly choose one nonzero element in each row of matrix

조회 수: 2 (최근 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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by