0

In my application A and jj are given as flattened, 1-dim numpy arrays. jj has not a strictly regular pattern. We can address the slice jj of A with:

A = np.arange(10)
jj = np.array([3,5,6])
A[jj]

This is called 'fancy slicing' and is told to be slow. Is there a way to speed up the access with something like:

A = np.arange(10)
jj = np.array([3,5,6])
ii = slice(jj)
A[ii]

This example does not work, but perhaps there is another lean way. The slice-command is fast and attractive. Is there a way to cast the jj numpy-array into a slice(jj) with a gain of efficiency?

My context is to build repeated a large system matrix in computational fluid dynamics with variable coefficients. Thanks for some hints!

dspencer
  • 4,297
  • 4
  • 22
  • 43
pyano
  • 1,885
  • 10
  • 28
  • A python `slice` has 3 values - start, stop, step. – hpaulj Jan 25 '19 at 15:47
  • If you can produce your `jj` with a `np.arange` or `range` call, it can be cast as a `slice`. But to understand the relative speed of slices, you have to understand the difference between a `view` and `copy`, and ultimately some idea of how `numpy` uses `strides` and `shape` to view a flat data array as a multidimensional one. – hpaulj Jan 25 '19 at 16:18

1 Answers1

3

Unfortunately, as you don't have a regular pattern, there is no better way than fancy indexing. It's the only way.

The reason why it's slower is that slice indexing doesn't copy the value, as you can create a view with the strides that are required. For irregular patterns, you can only copy data. Hence it's going to be slower.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62