簡體   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