繁体   English   中英

将以下代码从 Matlab 转换为 Python

[英]Convert the following code from Matlab to Python

我是 Python 新手,我正在尝试将以下代码从 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

任何帮助表示赞赏!

谢谢

您将 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)

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()

图片

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM