-3

Is there a way to convert a complex matrix to an integer matrix in python? Solution in Wolfram Mathematica . E. g.

import numpy as np
A=np.zeros((6,6),dtype=complex)
A[1,1]= 1.+1j
A[3,2]= 2.1-1j
print(A)

returns

[[0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j]
 [0. +0.j 1. +1.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j]
 [0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j]
 [0. +0.j 0. +0.j 2.1-1.j 0. +0.j 0. +0.j 0. +0.j]
 [0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j]
 [0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j]]

But i would like to have something like

[[0 0   ...
 [0 1+j ...  

I have tried

A.astype(np.int64)

but returns

... ComplexWarning: Casting complex values to real discards the imaginary part
  Entry point for launching an IPython kernel.
array([[0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 2, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])
jset
  • 1
  • 2
  • Hi, welcome to SO. For a good question you should post the code that you have tried. You could at least provide the matrices you have created and what library you already tried. – Juho Rutila Oct 11 '19 at 10:06

1 Answers1

0

What about the following:

import numpy as np

x = np.array([[12.0, 12.51 + 1.44J], [2.34 + 1.2J, 7.98 - 3.4J] ])

y = np.int_(x.real) + (np.int_(x.imag))*1J

Then you can in principle substitute np.int_ with other functions (floor, round etc etc).

gboffi
  • 22,939
  • 8
  • 54
  • 85
  • Have you tried your code before posting? Multiplying by `1j` casts the result to a Complex, that in Python is, loosely speaking, the union of two Floats. When you sum an Integer and a Complex, the integer is cast to a complex with null imaginary part and the result is still a Complex, i.e., two Floats. I could have spared to me, to you and to the rest of the audience all of this tirade if you tried your code before posting. – gboffi Oct 11 '19 at 10:39
  • Thank you GuaCaLa, it works for real numbers but not for complex. – jset Oct 11 '19 at 11:11