Select elements from only three consecutive columns.

3 views (last 30 days)
AM-Laurentian on 4 Apr 2019
Answered: AM-Laurentian on 5 Apr 2019
Hello all,
I have a 12 by 12 matrix, and I want to select 10 random elements. The elements should be from only three consecutive columns.
For example, I want to use 10 random elements from columns (1, 2, 3) or they could be from columns (2, 3, 4) or columns(3, 4, 5) and so on.
Thank you
AM-Laurentian on 5 Apr 2019
I am really sorry, it was a mistake. I realized that the question was submitted twice, I tried to delete it as soon as it was submitted but I could not. I apologies for any inconvenience.

Guillaume on 5 Apr 2019
Edited: Guillaume on 5 Apr 2019
startcolumn = randi(size(yourmatrix, 2) - 2); %select 1st of 3 consecutive column at random
candidateelements = yourmatrix(:, startcolumn : startcolumn + 2); %elements from the 3 consecutive columns
selectedelements = candidateelements(randperm(numel(candidateelements), 10)); %take 10 of these at random
Guillaume on 5 Apr 2019
For that, it would have been better to start a new question as this is a completely different scenario.
[ux, ~, rows] = unique(yourmatrix(:, 2)); %get unique values and matching rows
startx = randi(numel(ux) - 2); %start index of 3 consecutive x
rowpool = find(ismember(rows, startx:startx + 2)); %row index of all rows within selected 3 consecutive x
selectedrows = rowpool(ranpderm(numel(rowpool, 10))); %take 10 rows at random out of the pool

AM-Laurentian on 5 Apr 2019
Thank you so much Guillaume; It is very helpful.