Ensure same random coordinates do not appear twice

5 views (last 30 days)
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 Comments
Stephan
Stephan on 13 Oct 2018
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

Sign in to comment.

Answers (3)

Stephan
Stephan on 13 Oct 2018
Edited: Stephan on 13 Oct 2018
Hi,
use randperm for getting unique values:
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
Image Analyst on 13 Oct 2018
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
Bruno Luong on 13 Oct 2018
Edited: Bruno Luong on 13 Oct 2018
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);

Community Treasure Hunt

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

Start Hunting!