Ensure same random coordinates do not appear twice
显示 更早的评论
I am simulating a grid of 200*200 cells. I am doing this by creating two arrays of random numbers, and plotting them in a scatterplot.
x=randi(200,1,1000);
y=randi(200,1,1000);
figure(1);scatter(x,y);
what I am trying to do is add something additional, if any of these random coordinates are the same, then create additional x&y values that are not the same, for whenever this occurs. To ensure that the same coordinates do not appear twice at any time.
2 个评论
Stephan
2018-10-13
See my answer.
I looked at the questions you asked here so far. You can accept and / or vote for helpful answers in order to help people with similar Problems find helpful answers.
Also this is somehow a thank you to the volunteer contributers here, which get reputation by accepted answers.
Best regards
Stephan
Star Strider
2018-10-13
回答(3 个)
Hi,
For p = randperm(n,k), p contains k unique values. randperm performs k-permutations (sampling without replacement). To allow repeated values in the output (sampling with replacement), use randi(n,1,k).
randperm uses the same random number generator as rand, randi, and randn. You control this generator with rng.
Best regards
Stephan
Image Analyst
2018-10-13
Try this:
numCellsWide = 200;
numCellsOccupied = 1000;
[x, y] = meshgrid(1:numCellsWide, 1:numCellsWide);
indexes = randperm(numCellsWide * numCellsWide, numCellsOccupied);
x = x(indexes);
y = y(indexes);
plot(x, y, 'b.', 'MarkerSize', 18);
grid on;
xlabel('x', 'FontSize', 20);
ylabel('y', 'FontSize', 20);
caption = sprintf('%d points', numCellsOccupied);
title(caption, 'FontSize', 20);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);

Bruno Luong
2018-10-13
编辑:Bruno Luong
2018-10-13
You can do by rejection
margin = 1.2;
n = 1000;
xy = [];
mxy = 0;
while mxy < n
m = ceil(margin*n)-mxy;
xy = unique([xy; randi(200,m,2)],'rows');
mxy = size(xy,1);
end
x = xy(1:n,1);
y = xy(1:n,2);
or direct method
n = 1000;
i = randperm(200*200,n);
[x,y] = ind2sub([200 200], i);
类别
在 帮助中心 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!