2

I have defined a Fortran contiguous array:

   import numpy as np

   hp  = np.zeros([number_fragments, max(length_fragments_list), 6], order='F')

Slices of this array are not Fortran contiguous. How can I fix that?

hn = hp[0,0:Length-1,:]

   hn.flags

  C_CONTIGUOUS : False

  F_CONTIGUOUS : False

also

   hn = hp[0,0:Length-1,:].copy()

   hn.flags

  C_CONTIGUOUS : True

  F_CONTIGUOUS : False

How can I get, easily, Fortran contiguous arrays after slicing?

  • I usually don't pay attention to the `flags` attribute. Understanding the `strides` is better. Sometimes I also look at `hn.__array_interface__`. – hpaulj Sep 13 '19 at 17:30
  • Thanks. unfortunately, when I send the sliced array to a Fortran wrapped function, it says the input is not Fortran contiguous. So, it needs fixing. – Davood Norouzi Sep 13 '19 at 17:33
  • 1
    With 'F' order the last dimension is the outer one. Indexing like `hp[:,:-1, 0]` keeps the 'F' continuity (but would break 'C' continuity of an initially 'C' array). `copy` takes an order parameter. – hpaulj Sep 13 '19 at 18:48

1 Answers1

5

You can apply the numpy function np.asfortranarray on your slice to enforce it, example:

 np.asfortranarray(hp[0,0:Length-1,:].copy())
dtrckd
  • 657
  • 7
  • 17
  • 1
    @DavoodNorouzi, cool, don't hesitate to validate/lvl up the answer so ;) – dtrckd Sep 13 '19 at 17:40
  • 1
    Is the `copy` needed after `asfortranarray`? I think `hp[0,0:Length-1,:].copy(order='F')` would also work. – hpaulj Sep 13 '19 at 18:44
  • @hpaulj, `asfortranarray` alone, from what I experienced, don't copy the value. So yes, your solution seems to be more appropriate in the case where a copy of the array is needed. – dtrckd Sep 13 '19 at 23:42
  • The actual code is `np.array(a, dtype, copy=False, order='F', ndmin=1)`. `copy=False` means don't copy if you don't have to, but you may if needed. – hpaulj Sep 14 '19 at 00:11