Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compute matrix quadratic form in Julia

Tags:

matrix

julia

Given a Vector denoted v and Matrix denoted M, what is the fastest method for computing the matrix quadratic form in Julia, i.e. v'Mv? What about the most elegant?

Note: I would like the return value to be a scalar. Interestingly, if v = rand(3) and M = rand(3, 3), then v'*M*v returns a vector containing one element, not a scalar. I was not expecting this behaviour, although have read enough github issue pages to suspect there is a good reason for this behaviour that I'm just not smart enough to see. So, obviously (v'*M*v)[1] will do the job, just wondering if there is a better method...

like image 565
Colin T Bowers Avatar asked Jan 07 '23 21:01

Colin T Bowers


2 Answers

One option that returns a scalar is dot(v, M*v).

like image 152
David P. Sanders Avatar answered Feb 24 '23 08:02

David P. Sanders


How about a double for? Would save allocations of intermediate vector. For completeness, in code:

vMv{T}(v::Vector{T},M::Matrix{T}) = begin
    size(M) == (size(v,1),size(v,1)) || throw("Vector/Matrix size mismatch")
    res = zero(T)
    for i = 1:size(v,1)
        for j = 1:size(v,1)
            res += v[i]*v[j]*M[i,j]
        end
    end
    res
end

Adding some @inbounds and perhaps @simds would optimize.

like image 42
Dan Getz Avatar answered Feb 24 '23 07:02

Dan Getz