Carodusi
Carodusi

Reputation: 1

Why is Numpy.gradient returning a list instead of ndarray ?

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'>

Upvotes: 0

Views: 1282

Answers (1)

hpaulj
hpaulj

Reputation: 231395

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

Upvotes: 1

Related Questions