Get a set of 10000 unique random 2-D coordinates
7 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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)
0 个评论
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!