Skip to content

Instantly share code, notes, and snippets.

@mkitti
Created January 20, 2020 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkitti/563abe16c9ea6f4a95b7292e7c9c12ff to your computer and use it in GitHub Desktop.
Save mkitti/563abe16c9ea6f4a95b7292e7c9c12ff to your computer and use it in GitHub Desktop.
Sample pairs of values from vectors x and y without replacement
import StatsBase
"""
xs,ys = samplePairs(x,y,nSamples=length(x)*length(y))
Samples a pair of values, one from x and one from y, without repetition
"""
function samplePairs(x::AbstractVector{T}, y::AbstractVector{T}; nSamples=length(x)*length(y)) where {T}
xout = Vector{T}(undef,nSamples)
yout = Vector{T}(undef,nSamples)
p = length(x)*length(y)
s = zeros(Int,nSamples)
StatsBase.knuths_sample!(1:p,s)
@inbounds idx = CartesianIndices((length(x),length(y)))[s];
@inbounds for i = 1:nSamples
xout[i] = x[ idx[i][1] ]
yout[i] = y[ idx[i][2] ]
end
return xout, yout
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment