I am new to Python and I am trying to convert and modify the following code from Matlab to python:
This is what I have so far ( I am also trying to make it for 3 dimensions):
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
However, I am having a problem in the last if statement:
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
Any help is appreciated!
Thanks
you assign numpy float to those variables. those variables should be list
firstX = x[0] # all numpy.float64
firstY = y[0]
firstZ = z[0]
you should append new point to list
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 and firstZ are numbers so you can't use firstX[index]. So define them as list or array (if you know the final length).
I read your matlab code, I corrected it and plotted accordingly.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.