0

I have a numpy.ndarray of 3D and I need to calculate its gradient and obtain a new ndarray with the same dimensions. I'm using numpy.gradient to do so but it is returning a list instead. How can I get np.gradient to return a np.ndarray?

    force = np.gradient(phi)*(-1)

Where phi is my 300³ matrix and I keep obtaining

    print(type(force))
    type : <class 'list'>
2
  • 2
    The code you've shown shouldn't produce the output you've shown; gradient should return an array, and print(type(force)) shouldn't produce output in that format. Can you strip your code down to the bare minimum that still contains the buggy part and still demonstrates the bug when you run it, then post that? Commented Apr 6, 2015 at 3:26
  • 1
    give us phi so we can replicate your result. this is weird, because the docstring for gradient says it should return a list. have you checked whether np.gradient(phi) -- i.e., sans the *(-1) -- is a list? Commented Apr 6, 2015 at 3:26

1 Answer 1

1

The docs say gradient returns a (list of) N arrays of the same shape asfgiving the derivative offwith respect to each dimension.

An example in np.gradient returns a list - a list of 2 arrays

In [105]: np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float))
Out[105]: 
[array([[ 2.,  2., -1.],
       [ 2.,  2., -1.]]),
 array([[-0.5,  2.5,  5.5],
       [ 1. ,  1. ,  1. ]])]

A 1d input produces an array

In [106]: np.gradient(np.array([1, 2, 6], dtype=np.float))
Out[106]: array([-0.5,  2.5,  5.5])

A 3d array gives me a list of 3 arrays:

In [110]: len(np.gradient(np.ones((30,30,30))))
Out[110]: 3
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.