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

20 views (last 30 days)
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

Accepted Answer

John D'Errico
John D'Errico on 1 Feb 2021
Edited: John D'Errico on 1 Feb 2021
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 Comment
Mohammed Al-Fadhli
Mohammed Al-Fadhli on 1 Feb 2021
Yeah I realize that this problem can be solved with many different methods. Thanks for the answer! =)

Sign in to comment.

More Answers (1)

Alan Stevens
Alan Stevens on 1 Feb 2021
How about
P = randperm(64);
[I,J] = ind2sub([8,8],P);
x = I(1:8);
y = J(1:8);
  3 Comments
Alan Stevens
Alan Stevens on 1 Feb 2021
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

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!