Creating an array of unique random points
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Walter Roberson
2018-9-7
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 个评论
Walter Roberson
2018-9-7
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
2018-9-7
gives an example of creating unique random permutations, showing a loop that keeps generating until it has enough unique rows.
Image Analyst
2018-9-8
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 个评论
Walter Roberson
2018-9-8
"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")
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!