将以下代码从Matlab转换为Python

时间:2019-06-25 17:56:48

标签: python matlab numpy

我是Python的新手,我正尝试将以下code从Matlab转换和修改为python:

到目前为止,这是我所拥有的(我也尝试将其制作成3维):

import random
import numpy as np

L = 21.1632573
x = np.random.uniform(low=0.0000,high=L,size=10000) 
y = np.random.uniform(low=0.0000,high=L,size=10000) 
z = np.random.uniform(low=0.0000,high=L,size=10000) 


prox = 1
N = 20

#First Point
firstX = x[0]
firstY = y[0]
firstZ = z[0]

counter = 0
for k in range(1,N):
    thisX = x[k]
    thisY = y[k]
    thisZ = z[k]
    distances = np.sqrt((thisX-firstX)**2+(thisY-firstY)**2+(thisZ-firstZ)**2)
    minDistance = np.min(distances)
    if minDistance >= prox:
        firstX[counter] = thisX
        firstY[counter] = thisY
        firstZ[counter] = thisZ
        counter = counter + 1

但是,我在最后一个if语句中遇到问题:

File "/home/aperego/codes/LJ_Problem1/canonical/randomParticles.py", 
line 26, in <module> firstX[counter] = thisX

TypeError: 'numpy.float64' object does not support item assignment

感谢您的帮助!

谢谢

2 个答案:

答案 0 :(得分:1)

您将numpy float分配给这些变量。这些变量应该是列表

firstX = x[0]  # all numpy.float64
firstY = y[0]
firstZ = z[0]

您应该将新点添加到列表中

import random
import numpy as np

L = 21.1632573
x = np.random.uniform(low=0.0000,high=L,size=10000) 
y = np.random.uniform(low=0.0000,high=L,size=10000) 
z = np.random.uniform(low=0.0000,high=L,size=10000) 


prox = 1
N = 20

#First Point
firstX = [x[0]]
firstY = [y[0]]
firstZ = [z[0]]

for k in range(1,N):
    thisX = x[k]
    thisY = y[k]
    thisZ = z[k]
    distances = np.sqrt((thisX-firstX[0])**2+(thisY-firstY[0])**2+(thisZ-firstZ[0])**2)
    minDistance = np.min(distances)
    if minDistance >= prox:
        firstX.append(thisX)
        firstY.append(thisY)
        first.append(thisZ)

答案 1 :(得分:0)

firstX,firstY和firstZ是数字,因此您不能使用firstX [index]。因此,将它们定义为列表或数组(如果您知道最终长度)。

我阅读了您的matlab代码,对其进行了更正并作了相应的绘制。

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

L = 21.1632573
x = np.random.uniform(low=0.0000,high=L,size=10000) 
y = np.random.uniform(low=0.0000,high=L,size=10000) 
z = np.random.uniform(low=0.0000,high=L,size=10000) 

prox = 1
N = 20

#First Point
firstX = [x[0]]
firstY = [y[0]]
firstZ = [z[0]]

counter = 0
for k in range(1,N):
    distances = np.sqrt((x[k]-firstX)**2+(y[k]-firstY)**2+(z[k]-firstZ)**2)
    minDistance = np.min(distances)
    if minDistance >= prox:
        firstX.append(x[k])
        firstY.append(y[k])
        firstZ.append(z[k])
        counter = counter + 1

##Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(firstX,firstY,firstZ, c='b', marker='*')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

image