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!

2
  • A python slice has 3 values - start, stop, step. Commented Jan 25, 2019 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. Commented Jan 25, 2019 at 16:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.