Reputation: 405
A rather simple problem, and yet I dont seem to find any solution to it:
I am trying to use the differentiation of two arrays within an array and insert it as a new result into a new array... I hope the code clarifies this intention, even though it is not working, as python is telling me that it cannot combine a sequence with array calculation... How can I go around this problem? Thanks in advance!
MeteorNum = 5
#Coordinate Setup:
XPos = np.random.randint(0, 600, (MeteorNum,1))
YPos = np.random.randint(0, 800, (MeteorNum,1))
XYPos = np.hstack((XPos,YPos))
XYPos = np.vstack((XYPos, XYPos[0]))
print XYPos
#Distances:
r = np.zeros((MeteorNum,MeteorNum))
for i in range(0, MeteorNum):
for x in range(0, MeteorNum):
r[x,i] = (XYPos[x,:] - XYPos[i,:])
r = r*10**5
print r
and here the error I get:
runfile('C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments/week_5 Gravity simu.py', wdir='C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments')
[[249 660]
[256 605]
[119 423]
[422 398]
[480 504]
[249 660]]
Traceback (most recent call last):
File "<ipython-input-57-4cd9cc29ece0>", line 1, in <module>
runfile('C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments/week_5 Gravity simu.py', wdir='C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments')
File "C:\Users\Marco DS\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Users\Marco DS\Anaconda\lib\site- packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments/week_5 Gravity simu.py", line 37, in <module>
r[x,i] = (XYPos[x,:] - XYPos[i,:])
ValueError: setting an array element with a sequence.
Upvotes: 2
Views: 5096
Reputation: 31040
To remove errors, I think you need an extra dimension, of size 2, in your array r
:
r = np.zeros((MeteorNum,MeteorNum,2))
As XYPos[x,:] - XYPos[i,:]
in your for loop has a shape of (2,)
This returns a single array of shape (5, 5, 2)
.
Upvotes: 1
Reputation: 10398
try to add dtype=
in the container array:
MeteorNum = 5
#Coordinate Setup:
XPos = nprand.randint(0, 600, (MeteorNum,1))
YPos = nprand.randint(0, 800, (MeteorNum,1))
XYPos = np.hstack((XPos,YPos))
XYPos = np.vstack((XYPos, XYPos[0]))
print XYPos
#Distances:
r = np.zeros((MeteorNum,MeteorNum),dtype=np.ndarray)
for i in range(0, MeteorNum):
for x in range(0, MeteorNum):
r[x,i] = (XYPos[x,:] - XYPos[i,:])
r = r*10**5
print r
EDIT
The dtype argument indicate the desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
Upvotes: 2