0

I have the following example string:

s ="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!

4
  • What should the matrix result be in this example? And do you mean that the string contains the literal characters s and =, or do you mean that you assigned the string to a variable like s = "1 1+i\n1-i 0"? Commented Aug 21, 2022 at 15:36
  • I assigned the string to a variable s. The result should be matrix = np.array([[1, complex(1,1)], [complex(1, -1), 0]]) Commented Aug 21, 2022 at 15:40
  • 1
    Please edit your question to show this. And also answer all my questions. Commented Aug 21, 2022 at 15:41
  • In python a string is surrounded by double or single quotes. Commented Aug 22, 2022 at 3:34

1 Answer 1

0

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.