在Julia 1.0中提高循环速度

时间:2019-03-14 18:53:47

标签: julia

我有一个长矢量V和一个大矩阵M。我的目的在下面的Julia代码中。

using LinearAlgebra
function myfunction(M,V)
    n = size(V,1)
    sum = 0
    summ = 0
    for i = 1:n-1
        for j = i+1:n
            a= [i,j]
            Y = V[a]
            X = M[a,a]
            sum += Y'*inv(X)*Y
            summ += tr(X)*Y'*Y
        end
    end
return sum, summ
end
M = randn(10000,10000)
V = randn(10000)
@time myfunction(M,V)

由于向量非常长且矩阵很大,因此此过程需要很长时间。我在这个问题上花了很长时间。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

我只是手动展开计算以避免分配:

function myfunction2(M::AbstractMatrix{T},V::AbstractVector{T}) where {T}
    n = size(V, 1)
    sum = zero(T)
    summ = zero(T)
    for i = 2:n
        for j = 1:i-1
            @inbounds y1, y2 = V[i], V[j]
            y11 = y1*y1
            y12 = y1*y2
            y22 = y2*y2
            @inbounds a, b, c, d = M[i,i], M[i,j], M[j,i], M[j,j]
            sum += (d*y11-(c+b)*y12+a*y22) / (a*d-b*c)
            summ += (a+d)*(y11+y22)
        end
    end
    return sum, summ
end

(请注意,我对MV作了明确的假设)

编辑,这至少要快

function myfunction3(M::AbstractMatrix{T},V::AbstractVector{T}) where {T}
    n = size(V, 1)
    sum = zero(T)
    summ = zero(T)
    for i = 2:n
        @inbounds y1 = V[i]
        @inbounds a = M[i,i]
        y11 = y1*y1
        for j = 1:i-1
            @inbounds y2 = V[j]
            y12 = y1*y2
            y22 = y2*y2
            @inbounds b, c, d = M[i,j], M[j,i], M[j,j]
            sum += (d*y11-(c+b)*y12+a*y22) / (a*d-b*c)
            summ += (a+d)*(y11+y22)
        end
    end
    return sum, summ
end