Advanced indexing for sympy?

1.1k views Asked by At

With numpy, I am able to select an arbitrary set of items 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 does not seem to work with sympy matrices, as the code:

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

results to 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 whether there would be a way to do this in sympy?

1

There are 1 answers

1
Holt On BEST ANSWER

Your a and b does not represent similar objects, actually a is a 1x3 "matrix" (one row, 3 columns), namely a vector, while b is a 3x1 matrix (3 rows, one column).

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

The numpy equivalent would be numpy.array([[1], [2], [3]]), not your a.

Knowing that, b[[0,2]] has no meaning because you are missing index for one of your dimension. If you want to select only the first and third rows, you need to specify the second dimension:

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

Note: Using numpy, you could access a 3x1 matrix the way you want, it looks like simply is more strict than numpy.