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...
One option that returns a scalar is dot(v, M*v)
.
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 @simd
s would optimize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With