Ensure same random coordinates do not appear twice

조회 수: 11 (최근 30일)
Patrick Carey
Patrick Carey 2018년 10월 13일
답변: Image Analyst 2018년 10월 13일
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
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

댓글을 달려면 로그인하십시오.

답변 (3개)

Stephan
Stephan 2018년 10월 13일
편집: Stephan 2018년 10월 13일
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 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
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);

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by