Randomly choose one nonzero element in each row of matrix
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Peter Uwsen
el 9 de Jun. de 2022
Comentada: Peter Uwsen
el 14 de Jun. de 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!
0 comentarios
Respuesta aceptada
David Hill
el 9 de Jun. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!