Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid that cor(x,x) != 1... #17464

Merged
merged 1 commit into from
Jul 25, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 21 additions & 20 deletions base/statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -368,25 +368,6 @@ function corzm(x::AbstractMatrix, vardim::Int=1)
c = unscaled_covzm(x, vardim)
return cov2cor!(c, sqrt!(diag(c)))
end
function corzm(x::AbstractVector, y::AbstractVector)
n = length(x)
length(y) == n || throw(DimensionMismatch("inconsistent lengths"))
x1 = x[1]
y1 = y[1]
xx = abs2(x1)
yy = abs2(y1)
xy = x1 * conj(y1)
i = 1
while i < n
i += 1
@inbounds xi = x[i]
@inbounds yi = y[i]
xx += abs2(xi)
yy += abs2(yi)
xy += xi * conj(yi)
end
return xy / (sqrt(xx) * sqrt(yy))
end
corzm(x::AbstractVector, y::AbstractMatrix, vardim::Int=1) =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are packages calling this method? may be safer to deprecate

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so. I checked and I've only seen @simonster using it for WIP. It's not exported so deprecating it also a little bit messy.

cov2cor!(unscaled_covzm(x, y, vardim), sqrt(sumabs2(x)), sqrt!(sumabs2(y, vardim)))
corzm(x::AbstractMatrix, y::AbstractVector, vardim::Int=1) =
Expand All @@ -398,7 +379,27 @@ corzm(x::AbstractMatrix, y::AbstractMatrix, vardim::Int=1) =

corm{T}(x::AbstractVector{T}, xmean) = one(real(T))
corm(x::AbstractMatrix, xmean, vardim::Int=1) = corzm(x .- xmean, vardim)
corm(x::AbstractVector, xmean, y::AbstractVector, ymean) = corzm(x .- xmean, y .- ymean)
function corm(x::AbstractVector, mx::Number, y::AbstractVector, my::Number)
n = length(x)
length(y) == n || throw(DimensionMismatch("inconsistent lengths"))
n > 0 || throw(ArgumentError("correlation only defined for non-empty vectors"))

@inbounds begin
# Initialize the accumulators
xx = zero(sqrt(x[1] * x[1]))
yy = zero(sqrt(y[1] * y[1]))
xy = zero(xx * yy)

@simd for i = 1:n
xi = x[i] - mx
yi = y[i] - my
xx += abs2(xi)
yy += abs2(yi)
xy += xi * yi'
end
end
return clamp(xy / max(xx, yy) / sqrt(min(xx, yy) / max(xx, yy)), -1, 1)
end
corm(x::AbstractVecOrMat, xmean, y::AbstractVecOrMat, ymean, vardim::Int=1) =
corzm(x .- xmean, y .- ymean, vardim)

Expand Down