Selecting random cells in a matrix without repetition

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.

 Akzeptierte Antwort

dpb
dpb am 1 Okt. 2021
Bearbeitet: dpb am 1 Okt. 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.

4 Kommentare

Thanks dpb. However, I am getting an array out of bounds error in R=M(randperm(numel(M)),N2Choose);
Lorson Blair
Lorson Blair am 1 Okt. 2021
Bearbeitet: Lorson Blair am 1 Okt. 2021
Also, I'm trying to get the cell (keep track of the cells - row and column). I'll use the values later. One way I was thinking about doing it is to select the rows and columns separately and then perform some sort of comparison which seems overly complicated.
One parentheses was out of place on dpb's example:
M = rand(10);
N2Choose=20;
idx = randperm(numel(M), N2Choose) % the indices
idx = 1×20
31 46 11 16 79 30 40 90 3 36 47 6 81 94 96 66 2 89 83 42
[r,c] = ind2sub(size(M), idx) % if you need row/column
r = 1×20
1 6 1 6 9 10 10 10 3 6 7 6 1 4 6 6 2 9 3 2
c = 1×20
4 5 2 2 8 3 4 9 1 4 5 1 9 10 10 7 1 9 9 5
R=M(idx) % the values
R = 1×20
0.0584 0.3064 0.4200 0.4720 0.8760 0.4465 0.7343 0.7369 0.6275 0.2472 0.9182 0.7630 0.1024 0.7336 0.3009 0.4893 0.5159 0.3713 0.5391 0.0316
Thanks for this guys. Really helpful.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by