2

I have the following symmetric matrix in sympy:

m = sympy.Matrix([[x**2, x**3, x**4],
                  [x**3, x**5, x**6],
                  [x**4, x**6, x**7]])

My goal is to obtain the upper triangle of this matrix as a flattened array, like [x**2, x**3, x**4, x**5, x**6, x**7], that can be processed by lambdify.

I used In numpy to auxiiate achieving this:

f = lambdify((x), sympy.Matrix(np.array(m)[np.triu_indices(m.shape[0])]))

So that f(2.) gives:

[[   4.    8.   16.   32.   64.  128.]]

The questions is:

  • is there a native way to do this in sympy?

Bonus:

  • is there a way to obtain a 1D-array instead of a matrix?
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
  • is there any specific reason you prefer a sympy solution over a numpy one? Because otherwise, sympy is quite slow compared to numpy EDIT: hmm you are the same guy from the previous question about using sympy, ;-) assuming you will change something in your code to avoid the integration than? or is it not related to that other question? – usethedeathstar Jul 08 '13 at 13:07
  • Yes, I am the same guy... this is totally related to the other question. I could achieve a [great integration performance using Cython, check here...](http://stackoverflow.com/a/17522695/832621) – Saullo G. P. Castro Jul 08 '13 at 13:20

1 Answers1

0

I don't think there's a function to do that directly in SymPy yet (but patches are welcome!). You could probably write one pretty easily.

One thing you can try is using cse

>>> print cse(a)
([(x0, x**3), (x1, x**4), (x2, x**6)], [Matrix([
[x**2,   x0,   x1],
[  x0, x**5,   x2],
[  x1,   x2, x**7]])])

This will keep you from evaluating the same expression more than once. If your actual expression really is just powers of x, you can probably code up something even more efficient by using the fact that there is a lot of duplicate work involved in computing all the powers of x.

asmeurer
  • 86,894
  • 26
  • 169
  • 240