How do i select a random cell with a certain value from the matrix

2 vues (au cours des 30 derniers jours)
Antonio Sarusic
Antonio Sarusic le 27 Mar 2020
Commenté : Adam Danz le 27 Mar 2020
Hello,
I have a 1024x1280 matrix that only has the values 0 and 1.
Now I want to randomly select a cell that has the value 1.
Anybody got an idea how to do that?
Thanks

Réponse acceptée

Adam Danz
Adam Danz le 27 Mar 2020
Modifié(e) : Adam Danz le 27 Mar 2020
% Create matrix of 0s & 1s
M = round(rand(1024, 1280));
% List all indices of 1s
loc = find(M==1);
% Randomly select one of the indices
randInd = datasample(loc, 1); % or randInd = loc(randi(numel(loc)))
% Show the row and col number of the selection
[row, col] = ind2sub(size(M), randInd);
  2 commentaires
Antonio Sarusic
Antonio Sarusic le 27 Mar 2020
Thank you very much!
Adam Danz
Adam Danz le 27 Mar 2020
Glad I could help!

Connectez-vous pour commenter.

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