Advanced indexing for sympy?

With numpy, I can select an arbitrary set of elements from an array with a list of integers:

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> a[[0,2]]
array([1, 3])

      

The same doesn't seem to work with sympy matrices, as the code:

>>> import sympy as sp
>>> b = sp.Matrix([1,2,3])
>>> b[[0,2]]

      

outputs an error message:

**Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/sympy/matrices/dense.py", line 94, in __getitem__
    return self._mat[a2idx(key)]
  File "/usr/lib/python2.7/dist-packages/sympy/matrices/matrices.py", line 4120, in a2idx
    raise IndexError("Invalid index a[%r]" % (j, ))
IndexError: Invalid index a[[0, 2]]

      

My question is, would there be a way to do this in sympy?

+3


source to share


1 answer


Your a

and b

do not represent similar objects, actually a

is a 1x3

"matrix" (a single row, column 3), namely a vector, and b

- 3x1

a matrix (3 row, one column).

>>> a
array([1, 2, 3])
>>> b
Matrix([
[1],
[2],
[3]])

      

The equivalent numpy

will be numpy.array([[1], [2], [3]])

, not yours a

.



Knowing that b[[0,2]]

doesn't make sense because you are missing an index for one of your dimensions. If you only want to select the first and third rows, you need to specify the second dimension:

>>> b[[0, 2], :]
Matrix([
[1],
[3]])

      

Note . By using numpy

, you can access the matrix the 3x1

way you want, it looks like it simply

is stricter than numpy

.

+2


source







All Articles