Get a set of 10000 unique random 2-D coordinates

조회 수: 5 (최근 30일)
Aaron J. Hendrickson
Aaron J. Hendrickson 2017년 2월 15일
편집: John D'Errico 2017년 2월 15일
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

채택된 답변

Star Strider
Star Strider 2017년 2월 15일
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)

추가 답변 (1개)

John D'Errico
John D'Errico 2017년 2월 15일
편집: John D'Errico 2017년 2월 15일
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.

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by