Is there a way to make array entries complex variables in NumPy?

1.6k views Asked by At

I am working with numpy arrays in Python. Is there a way to keep the entries of an array as variables so that they follow proper matrix multiplication and other matrix functions (addition, determinant, etc.)?

For example:

         import numpy as np
         A = np.array([[a, b], [c, d]])
         B = np.array([[e, f], [g, h]])
         C = np.dot(A,B)

         # C should be [ae+bf ag+bh]
         #             [ce+df cg+dh]

Also, as my matrix elements are complex in general, I would like the entries of the type a+ib where i is interpreted as imaginary root of 1 rather than a variable. I can write the code defining my own functions, but is there a clean way of doing it?

2

There are 2 answers

0
petem On BEST ANSWER

Use sympy:

from  sympy import *

A=MatrixSymbol('A', 2, 2)
B=MatrixSymbol('B', 2,2)
print Matrix(A)
print  Matrix(A*B)

>>>Matrix([[A[0, 0], A[0, 1]], [A[1, 0], A[1, 1]]])
   Matrix([[A[0, 0]*B[0, 0] + A[0, 1]*B[1, 0], A[0, 0]*B[0, 1] + A[0,  1]*B[1, 1]], [A[1, 0]*B[0, 0] + A[1, 1]*B[1, 0], A[1, 0]*B[0, 1] + A[1, 1]*B[1, 1]]])
0
Alex Huszagh On

See here: Complex numbers usage in python

Numpy respects Python imaginary numbers.

>>> a = np.array([i+1j for i in range(3)])
>>> b = np.array([i+2j for i in range(3,6)])
>>> a*b
array([-2.+3.j,  2.+6.j,  8.+9.j])

This works too with your given example (as expected):

>>> a
array([[ 1.+1.j,  1.+2.j],
       [ 1.+1.j,  1.+2.j]])
>>> b
array([[ 1.+1.j,  1.+2.j],
   [ 1.+1.j,  1.+2.j]])
>>> np.dot(a,b)
array([[-1.+5.j, -4.+7.j],
       [-1.+5.j, -4.+7.j]])

As for keeping them as variables, NumPy passes everything through it's Python interface to a lower-level C code, so I doubt you can store everything as a variable.

You could, however, write an arbitrary function that accomplishes this task:

def myfunc(obj):
     A = np.array([[obj['a']], [obj['b']]])
     B = np.array([[obj['c']], [obj['d']]])
     C = np.dot(A,B)
     return C