Julia - get the real part of a complex array

I need to split the variable z::Array{Complex128,1} into two arrays for real and complex parts. One way to do this is to create new variables ::Array{Float64,1} and populate them with an element by element:

 for i = 1:size(z)[1] ri[i] = z[i].re ii[i] = z[i].im end 

Is there a way to do this, not related to copying data, for example, to somehow manipulate the steps and offsets of z ?

+6
source share
1 answer

Change The original version used the unnecessary reshape operation. As @DNF noted in the comments, this was optional. The answer has been revised since.

In general, when copying is not a problem, just do real(z) and imag(z) (renamed real.(z) and imag.(z) to v0.6). I include this to help future readers who have a similar problem but who might not like copying.

As you can imagine, you can control z steps to avoid copying data. Just

 zfl = reinterpret(Float64, z) zre = @view zfl[1:2:end-1] zim = @view zfl[2:2:end] 

In combination, we observe that data copying is not performed (allocation is associated with array representations selected by the heap and minimal).

 julia> z = Vector{Complex128}(100000); julia> function reimvec(z) zfl = reinterpret(Float64, z) zre = @view zfl[1:2:end-1] zim = @view zfl[2:2:end] zre, zim end reimvec (generic function with 1 method) julia> @time reimvec(z); 0.000005 seconds (9 allocations: 400 bytes) 

As we see, behind the scenes, such an array alternates:

 julia> strides(reimvec(z)[1]) (2,) 
+7
source

All Articles