Selecting random cells in a matrix without repetition
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Lorson Blair
el 1 de Oct. de 2021
Comentada: Lorson Blair
el 1 de Oct. de 2021
Good day guys. This may be a simple question, but I cannot seem to find an answer on here for it. I am trying to select random cells in a matrix without repeating the cells. For example. I have a 10x10 matrix, and I'm trying to select 20 cells randomly without repeating the cells. Any help will be appreciated.
Thanks.
0 comentarios
Respuesta aceptada
dpb
el 1 de Oct. de 2021
Editada: dpb
el 1 de Oct. de 2021
N2Choose=20;
R=M(randperm(numel(M),N2Choose));
ERRATUM
Stupid auto-complete put the silly parens in instead of letting me when/where wanted...my story and I'm stickin' to it!!! :)
ADDENDUM
As far as the comment re: positions, just wrap the indices when generate them if those are the desired return values instead of the values.
[r,c]=ind2sub(randperm(numel(M),N2Choose),size(M));
In some ways this is less useful than the linear indices; you'll need arrayfun or similar construct to pull the elements that way as MATLAB will expand the two vectors to all combinations of each instead of just accessing the two vector elements pairwise.
I just answered another earlier this AM that is similar issue -- https://www.mathworks.com/matlabcentral/answers/1464664-feeding-index-returned-by-find-in-another-matrix#answer_799384
4 comentarios
Kelly Kearney
el 1 de Oct. de 2021
One parentheses was out of place on dpb's example:
M = rand(10);
N2Choose=20;
idx = randperm(numel(M), N2Choose) % the indices
[r,c] = ind2sub(size(M), idx) % if you need row/column
R=M(idx) % the values
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing 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!