I have arrays newx and newy with size nx*ns and ny*ns respectively where nx!=ny.
I want to be able to set the elements defined by newx and newy in array f by:

f = np.zeros([nx,ny,ns])
for s in range(ns):
    f[newx[:,s],newy[:,s],s] = s

Unfortunately this gives an error:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

I understand the error but for the life of me can't figure out the correct syntax. plz help out.

Edit: provided sample code:

import numpy as np

newx = np.array([[0,1],
                 [1,2],
                 [2,3],
                 [3,0]])
newy = np.array([[0,1],
                 [1,2],
                 [2,0]])

f = np.zeros([4,3,2])
for s in range(2):
    f[newx[:,s],newy[:,s],s] = s
有帮助吗?

解决方案

newx and newy must have the same shape , so you must reshape them.

f = np.zeros([4,3,2])

newX = newx.reshape(8,1)
newY = newy.reshape(6,)

for s in range(2):
    f[newX , newY ,s] = s


print f
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top