Ensure same random coordinates do not appear twice

10 ビュー (過去 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
Star Strider
Star Strider 2018 年 10 月 13 日

サインインしてコメントする。

回答 (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 Center および File ExchangeAnnotations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by