Get a set of 10000 unique random 2-D coordinates

7 views (last 30 days)
I have an array that is 512 rows by 256 columns (i.e Nrows=512, Ncols=256) and I want the 2-d coordinates of a random sample of size 10000 without replacement from this array. I managed to do this with the code below but is seems rather clunky. Seems like there is a cleaner way to do this. Any help appreciated.
Nrows=512; Ncols=256;
row_mat = zeros(Nrows,Ncols);
col_mat = zeros(Nrows,Ncols);
for i=1:Nrows
row_mat(i,:) = i;
end
for i=1:Ncols
col_mat(:,i) = i;
end
ind = [row_mat(:) col_mat(:)];
[temp,idx] = datasample(ind(:,1),10000,'Replace',false);
I = [ind(idx,1) ind(idx,2)]; % This is my list of 10000 unique random coordinates

Accepted Answer

Star Strider
Star Strider on 15 Feb 2017
See if this does what you want:
Array = rand(256,512); % Original Array (Created)
idx = randperm(numel(Array), 1E+4); % Generate Vector OF Random Indices
[row_sub,col_sub] = ind2sub(size(Array), idx); % Convert To Subscripts (If Necessary)
sub_mtx = [row_sub(:), col_sub(:)]; % Matrix Of Subscripts (Rows Of Matrix)

More Answers (1)

John D'Errico
John D'Errico on 15 Feb 2017
Edited: John D'Errico on 15 Feb 2017
Easy enough. Two lines of code, if you don't count that I defined N and Asize to make this somewhat general.
N = 10000;
Asize = [512,256];
[Ir,Ic] = ind2sub(Asize,randperm(prod(Asize),N));
I = [Ir',Ic'];
By the way, as you wrote it I'd STRONGLY suggest learning what the functions meshgrid and/or ndgrid do. Or, you might think about how you might create that matrix using a generalized outer product. bsxfun, for example. Even better, if you have the current release of MATLAB (R2016b or later), try this:
zeros(Nrows,1) + (1:Ncols)
The point is, start learning how to use vector and array operations in MATLAB, rather than loops.

Categories

Find more on Data Type Identification in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!