Home > Blockchain >  string to complex matrix representation in python
string to complex matrix representation in python

Time:08-22

I have the following example string:

1 1 i\n1-i 0

Now I have to turn this string into a complex matrix. I am aware of the np.matrix() function but it is not designed for a complex matrix. Maybe some of you can provide me some ideas of how I can go forward. I also tried to split at \n but then I have two arrays which contain exactly one element (1 1 i & 1-i 0 ). The result should be: np.array([[1, complex(1,1)], [complex(1, -1), 0]])

Thanks in advance!

CodePudding user response:

Your question has two parts.

First, we want to convert the string into a list of complex numbers (as strings), and then convert this list into the actual complex numbers.

s = "1 1 i\n1-i 0"

import re

complex_strings = re.split("\n|\s ", s.replace('i', 'j'))
complex_numbers = [complex(x) for x in complex_strings]
m = np.array(complex_numbers).reshape(2, 2)
[[1. 0.j 1. 1.j]
 [1.-1.j 0. 0.j]]
  • Related