1

complex to real+imag part

Given a complex array we can assign pointers to its real and imaginary part following the answer in https://stackoverflow.com/a/54819542

program main
  use iso_c_binding
  implicit none

  complex, target  :: z(2) = [(1,2), (3,4)]
  real,    pointer :: re(:), im(:), buf(:)

  call c_f_pointer(c_loc(z), buf, shape=[size(z)*2])

  re(1:2) => buf(1::2)
  im(1:2) => buf(2::2)

  print *, 'z', z
  print *, 're', re
  print *, 'im', im
end program

real+imag part to complex

My question is how to do it the other way around? Given two real arrays re,im. How can one assign a complex pointer z where the real part is given by re and imaginary part by im? Something similar to

program main
  implicit none

  real,    target  :: re(2)=[1,3], im(2)=[2,4]
  complex, pointer :: z(:)

  z => cmplx(re, im)    ! doesnt work as cmplx doesnt return a pointer result
end program

Is it even possible as re,im are not always contiguous in memory?

jack
  • 1,658
  • 1
  • 7
  • 18
  • 2
    It isn't possible, but the usual question is why you'd want to use pointers to do this. Could you explain what it is you are trying to do? (Note, for example, in most cases I'd be quite happy doing `z%re=[1.,2.,3.] ! Set real components` rather than use pointers.) – francescalus Nov 06 '20 at 09:22
  • Intel's mkl supplies an iterative solver dfgmres which only works for double precision. I need one for complex systems aka zfgmres. Thus, I want to switch between complex arrays and real ones (I am mapping the complex residual to a real array of double the length). Long story short: I want it to be efficient and not copy unnecessary data. – jack Nov 06 '20 at 09:27
  • actually, the real and imaginary part are in one (!) long array of contiguous memory s.t. I can use something similar as in the first example. – jack Nov 06 '20 at 10:03
  • Without copy, isn't it impossible to recast (or combine) two separate arrays for real and imag parts into a complex array? (because the Re and Im parts of each complex variable needs to be adjacent in memory..) – roygvib Nov 07 '20 at 13:24

0 Answers0