How to generate 8 random 2D coordinates that do not duplicate?

Hi!
So i wonder how to get 8 random (x,y) coordinates that won't duplicate. For example x=[1 1,1,2,8] and y=[1 2 3 2 7]. In this example there is no coordinates that repeat themselfs. But if for example x=[1,1,1,2,8] and y=[1,1,3,2,7] then the first and scound points duplicates beacuse they have same coordinates (1,1). Another condition is that the coordinates need to be integers from 1-8. Whith that said x should have a value from 1-8 and y should have a value from 1-8.
So i have tried with this code but i get duplicates :(.
clc; clear; close all;
x=[1:8];
y=[1:8];
P=[x;y];
P(randperm(16)) =P

 채택된 답변

John D'Errico
John D'Errico 2021년 2월 1일
편집: John D'Errico 2021년 2월 1일
Sorry. My first answer did not read your question carefully enough.
You want 8 sets of integer coordiantes from the lattice in (1:8)X(1:8).
[x,y] = meshgrid(1:8);
xy = [x(:),y(:)];
xysets = xy(randperm(64,8),:)
xysets = 8×2
3 4 8 3 4 7 7 1 6 6 7 4 7 7 1 7
Each row of that set is one (x,y) pair. Because randperm was used, you will never find a duplicated point in that set.
Are there other ways to solve this? YES. of course there are. The above seems the most direct. You could use sampling with a test to see if there were any dups. For example, this next call risks a duplicate pair:
randi([1,8],[8,2])
ans = 8×2
4 7 6 5 6 3 6 3 3 8 5 3 7 6 7 2
The solution is simple though.
flag = true;
while flag
xysets = unique(randi([1,8],[8,2]),'rows');
flag = size(xysets,1) ~= 8;
end
xysets
xysets = 8×2
1 8 2 8 3 8 5 5 5 7 7 6 7 7 8 4
The while loop simply resamples sets of pairs until it gets a set with all unique pairs. That will happen pretty quickly. In fact, the loop will require only one pass through MOST of the time.

댓글 수: 1

Yeah I realize that this problem can be solved with many different methods. Thanks for the answer! =)

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

추가 답변 (1개)

Alan Stevens
Alan Stevens 2021년 2월 1일
How about
P = randperm(64);
[I,J] = ind2sub([8,8],P);
x = I(1:8);
y = J(1:8);

댓글 수: 3

Very helpful. Could you plase give a little of explanation for what "ind2sub" do? Thanks alot for the help!
You have an 8x8 grid (8 x values and 8 y values), making 64 grid points in total. Think of them as numbered columnwise from 1 to 64. Shuffle these numbers (randperm). Then assume the shuffled numbers are rearranged into an 8x8 grid. The shuffled numbers are indices (ind) and the 8x8 grid has 2dimensional subscripts (sub). So ind2sub calculates the 2d subscripts that correspond to the 1d indices.
doc ind2sub
Thanks now i understand! =)

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

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by