## Select random elements from three consecutive columns in a big matrix?

### AM-Laurentian (view profile)

on 4 Apr 2019
Latest activity Commented on by AM-Laurentian

### AM-Laurentian (view profile)

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.
Thanks

Walter Roberson

### Walter Roberson (view profile)

on 5 Apr 2019
10 from each of the columns? 10 total from those 3 columns, with no effort to balance how many are to be taken from each individual column?
Guillaume

### Guillaume (view profile)

on 5 Apr 2019
And it looks like you delete your question once answered, which is not going to go down well with us (and will be restored anyway).
AM-Laurentian

### AM-Laurentian (view profile)

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.

### Walter Roberson (view profile)

on 5 Apr 2019

N = 10;
[r, c] = size(YourMatrix);
start_col = randi([1, c-2]);
chosen = YourMatrix(start_col * r - 1 + randi([1 3*r], 1, N));

AM-Laurentian

on 5 Apr 2019
Thanks a lot

### Jos (10584) (view profile)

on 5 Apr 2019
Edited by Jos (10584)

### Jos (10584) (view profile)

on 5 Apr 2019

M = magic(5) % input data
N = 4 % number of selections
nC = 3 % number of consecutive columns
% engine
szM = size(M)
r = randi(szM(1), N, nC) % N x 3 random rows
c = randi(szM(2) - nC + 1, N, 1) % N random first columns
c = c + [0:nC-1] % add consecutive columns
R = M(sub2ind(szM, r, c)) % index into M

AM-Laurentian

on 5 Apr 2019
Thank you.