Ensure same random coordinates do not appear twice
10 ビュー (過去 30 日間)
古いコメントを表示
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
回答 (3 件)
Stephan
2018 年 10 月 13 日
編集済み: Stephan
2018 年 10 月 13 日
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
0 件のコメント
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]);

0 件のコメント
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);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Annotations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!