huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11920

In numpy, how can I create a complex matrix?

At line

e[i][j][k]=np.divide(ftf[i][j][k],ftg[i][j][k])

while running below code,

'''

                            Online Python Compiler.
                Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.

'''
import numpy as np

f=np.zeros((2,2,2))
g=np.zeros((2,2,2))

f=np.add(f,1)
g=np.add(g,2)

for i in range(0,2):
    for j in range(0,2):
        for k in range(0,2):
            f[i][j][k] = (i+1)*(j+1)+(k+1)
            g[i][j][k] = (i+2)*(j+3)+(k+4)

ftf = np.fft.fftn(f)
ftg = np.fft.fftn(g)
print(f)
print(g)
print(ftf)
print(ftg)
print("------")
e =np.zeros((2,2,2))
for i in range(0,2):
    for j in range(0,2):
        for k in range(0,2):
            if np.isnan(ftg[i][j][k]):
                e[i][j][k]=0
            else:
                e[i][j][k]=np.divide(ftf[i][j][k],ftg[i][j][k])
print(e)
print("------")
h= np.fft.ifftn(e)

print(h)

an error is returned:

/home/main.py:36: ComplexWarning: Casting complex values to real discards the imaginary part
e[i][j][k]=np.divide(ftf[i][j][k],ftg[i][j][k])

I think I have to create e as complex. How can I create a complex matrix with zeros as elements?

Upvotes: 1

Views: 9212

Answers (1)

yatu
yatu

Reputation: 88236

Set the dtype argument in np.zeros to complex:

np.zeros((10,10), dtype=complex)

array([[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, 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],...

Upvotes: 3

Related Questions