Skip to content

Commit 71ebe28

Browse files
authored
Merge pull request #166 from JuliaStats/dw/cov_cor_optimization
Optimize `cov` and `cor` with identical arguments
2 parents 68869af + aa0f549 commit 71ebe28

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/Statistics.jl

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -604,8 +604,13 @@ default), computes ``\\frac{1}{n-1}\\sum_{i=1}^n (x_i-\\bar x) (y_i-\\bar y)^*``
604604
``*`` denotes the complex conjugate and `n = length(x) = length(y)`. If `corrected` is
605605
`false`, computes ``\\frac{1}{n}\\sum_{i=1}^n (x_i-\\bar x) (y_i-\\bar y)^*``.
606606
"""
607-
cov(x::AbstractVector, y::AbstractVector; corrected::Bool=true) =
608-
covm(x, mean(x), y, mean(y); corrected=corrected)
607+
function cov(x::AbstractVector, y::AbstractVector; corrected::Bool=true)
608+
if x === y
609+
cov(x; corrected=corrected)
610+
else
611+
covm(x, mean(x), y, mean(y); corrected=corrected)
612+
end
613+
end
609614

610615
"""
611616
cov(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims::Int=1, corrected::Bool=true)
@@ -614,8 +619,13 @@ Compute the covariance between the vectors or matrices `X` and `Y` along the dim
614619
`dims`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas
615620
the sum is scaled with `n` if `corrected` is `false` where `n = size(X, dims) = size(Y, dims)`.
616621
"""
617-
cov(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims::Int=1, corrected::Bool=true) =
618-
covm(X, _vmean(X, dims), Y, _vmean(Y, dims), dims; corrected=corrected)
622+
function cov(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims::Int=1, corrected::Bool=true)
623+
if X === Y
624+
cov(X; dims=dims, corrected=corrected)
625+
else
626+
covm(X, _vmean(X, dims), Y, _vmean(Y, dims), dims; corrected=corrected)
627+
end
628+
end
619629

620630
##### correlation #####
621631

@@ -746,15 +756,26 @@ cor(X::AbstractMatrix; dims::Int=1) = corm(X, _vmean(X, dims), dims)
746756
747757
Compute the Pearson correlation between the vectors `x` and `y`.
748758
"""
749-
cor(x::AbstractVector, y::AbstractVector) = corm(x, mean(x), y, mean(y))
759+
function cor(x::AbstractVector, y::AbstractVector)
760+
if x === y
761+
cor(x)
762+
else
763+
corm(x, mean(x), y, mean(y))
764+
end
765+
end
750766

751767
"""
752768
cor(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims=1)
753769
754770
Compute the Pearson correlation between the vectors or matrices `X` and `Y` along the dimension `dims`.
755771
"""
756-
cor(x::AbstractVecOrMat, y::AbstractVecOrMat; dims::Int=1) =
757-
corm(x, _vmean(x, dims), y, _vmean(y, dims), dims)
772+
function cor(x::AbstractVecOrMat, y::AbstractVecOrMat; dims::Int=1)
773+
if x === y
774+
cor(x; dims=dims)
775+
else
776+
corm(x, _vmean(x, dims), y, _vmean(y, dims), dims)
777+
end
778+
end
758779

759780
##### median & quantiles #####
760781

0 commit comments

Comments
 (0)