Creating an array of unique random points
2 views (last 30 days)
Show older comments
Hi all, I would like to create a 2D array which gives an X amount of unique random X and Y coordinates. I have no problem setting up the array but I am having trouble finding a way to detect and change duplicate values should they arise. Any help on finding a code that will find any duplicate values and change them to unique values would be appreciated, cheers.
0 Comments
Answers (2)
Walter Roberson
on 7 Sep 2018
unique() with 'rows' and 'stable'. Then check the size of the result, compare to the desired size to determine how many more entries you need. Random that many more, append to the end, go through the unique and size check...
I have posted the code a few times.
3 Comments
Walter Roberson
on 7 Sep 2018
Sorry I do not see it at the moment. I poked around im my old posts but I did not seem to find the right keywords.
Walter Roberson
on 7 Sep 2018
gives an example of creating unique random permutations, showing a loop that keeps generating until it has enough unique rows.
Image Analyst
on 8 Sep 2018
Why would there be any duplicate values if you're using floating point values like you'd get from rand().
I don't understand why you're using X for both the number of points, and the x coordinate. Let's call X N and then you can get random x and y coordinates like this
x = xMin + (xMax-xMin) * rand(N, 1);
y = yMin + (yMax-yMin) * rand(N, 1);
There will be no duplicated coordinates.
You would only have duplicates (possibly) if you restricted your x and y coordinates to integers.
1 Comment
Walter Roberson
on 8 Sep 2018
"There will be no duplicated coordinates."
Well, probably. But an RNG that cannot produce duplicates has a limited period.
"You would only have duplicates (possibly) if you restricted your x and y coordinates to integers."
rand() * 2^53 is certain to be an integer, but has the same duplicate properties as rand() has. So it is not integers that are the factors, but rather how many bits of output you are effectively using. If you are using N bits out of the 53, then you are certain to have a duplicate by 2^N entries, and probably by very much less ("birthday paradox")
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!