sympy index range of vector of symbols

Viewed 54

Hi I am trying to index a range of a vector of symbols.

My first idea was to use a MatrixSymbol

A = MatrixSymbol('A',10,1)
B = Matrix(A[0:2]) # does not work!

Then I thought I could use an IndexBased, but how do I generate the submatrix B (I can't index a range)

A=IndexedBased('A')
B=Matrix([A[0],A[1]]) # works but I want to define a range

There must be a proper way to do this.

1 Answers

IndexedBase will give you a 1-d vector like symbol.

You could use a list comprehension with a range giving the indices:

>>> a = IndexedBase("A")
>>> Matrix([a[i] for i in range(2)])
Matrix([
[A[0]],
[A[1]]])

Since you are working in Python, you are free to modify routines to suit your needs if you want to use direct slicing on the IndexedBase:

def gi(self, slc):
  if isinstance(slc, slice):
      a,b,s=slc.start, slc.stop, slc.step
      s = s or 1
      a = a or 0
      assert all(type(i) is int or i is None for i in (a,b,s))
      assert b is not None
      rv = []
      for i in range(a,b,s):
        rv.append(self[i])
      return rv
  return _gi(self, slc)

_gi = IndexedBase.__getitem__
IndexedBase.__getitem__ = gi

With that modification you ca now do:

>>> x = IndexedBase('x')
>>> x[0]
x[0]
>>> x[:2]
[x[0], x[1]]

(This does not attempt to handle the key words argument; it's more a proof of concept.)

Related