Select elements from only three consecutive columns.

3 views (last 30 days)
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.
Any help please.
Thank you
  2 Comments
AM-Laurentian
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.

Sign in to comment.

Accepted Answer

Guillaume
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
  2 Comments
Guillaume
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

Sign in to comment.

More Answers (1)

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

Community Treasure Hunt

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

Start Hunting!