Randomly choose one nonzero element in each row of matrix
2 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!