0
votes

Let's say I've a large N x M -sized matrix A (e.g. 1000 x 1000). Selecting k random elements without replacement from A is relatively straightforward in MATLAB:

A = rand(1000,1000);         % Generate random data
k = 5;                       % Number of elements to be sampled
sizeA = numel(A);            % Number of elements in A
idx = randperm(sizeA);       % Random permutation
B = A(idx(1:k));             % Random selection of k elements from A

However, I'm looking for a way to expand the above concept so that I could randomly select k non-overlapping n x m -sized sub-matrices (e.g. 5 x 5) from A. What would be the most convenient way to achieve this? I'd very much appreciate any help!

1

1 Answers

0
votes

This probably isn't the most efficient way to do this. I'm sure if I (or somebody else) gave it more thought there would be a better way but it should help you get started.

First I take the original idx(1:k) and reshape it into a 3D matrix reshape(idx(1:k), 1, 1, k). Then I extend it to the length required, padding with zeros, idx(k, k, 1) = 0; % Extend padding with zeros and lastly I use 2 for loops to create the correct indices

for n = 1:k
    for m = 1:k
        idx(m, 1:k, n) = size(A)*(m - 1) + idx(1, 1, n):size(A)*(m - 1) + idx(1, 1, n) + k - 1;
    end
end

The complete script built onto the end of yours

A = rand(1000, 1000);
k = 5;
idx = randperm(numel(A));
B = A(idx(1:k));

idx = reshape(idx(1:k), 1, 1, k);
idx(k, k, 1) = 0; % Extend padding with zeros
for n = 1:k
    for m = 1:k
        idx(m, 1:k, n) = size(A)*(m - 1) + idx(1, 1, n):size(A)*(m - 1) + idx(1, 1, n) + k - 1;
    end
end

C = A(idx);