Randomly choose one nonzero element in each row of matrix

10 vues (au cours des 30 derniers jours)
Peter Uwsen
Peter Uwsen le 9 Juin 2022
Commenté : Peter Uwsen le 14 Juin 2022
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!

Réponse acceptée

David Hill
David Hill le 9 Juin 2022
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

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by