To follow up on Dahua's comment:

If you're interested in using the fastest code, the code that Dahua posted is 
the fastest since it uses several clever tricks to get the absolute best speed.

If you're interested in writing a faster implementation than the one you wrote, 
you need to avoid allocating temporary arrays. You'd be better off with a loop 
like:

function mag_sqr{T}(x::Vector{Complex{T}})
    res = similar(x, T)
    for i in 1:length(x)
        res[i] = real(x[i]) * real(x[i]) + imag(x[i]) * imag(x[i])
    end
    return res
end

That way you only allocate the amount of memory required to produce the desired 
output.

 -- John

On Jul 16, 2014, at 11:28 AM, Dahua Lin <[email protected]> wrote:

> With the latest Julia, you can do this by 
> sumabs2(x)
> 
> Dahua
> 
> 
> On Wednesday, July 16, 2014 9:57:54 AM UTC-5, Neal Becker wrote:
> As a first exercise, I wanted to code magnitude squared of a complex 
> 1-d array.  Here is what I did: 
> 
> mag_sqr{T} (x::Array{Complex{T},1}) = sum(real(x).*real(x)+imag(x).*imag(x)) 
> 
> Is this a "good" approach?  I'm wondering if it's not very efficient, since I 
> expect it would compute matrixes of element-wise products first, rather than 
> doing the sum as a running summation (like a loop in c++). 
> 
> Can you suggest something "better"? 
> 

Reply via email to