0

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
2
  • Show us complete working code. Commented Apr 8, 2014 at 13:58
  • newx and newy don't make any sense. If you want to set to s the elements at some coordinates, you should have that number of x,y,s triplets rather than a different number of x,s and y,s pairs. Commented Apr 8, 2014 at 15:11

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ok got it, your tip that the newx and newy should be the same size was the solution. thx
Or better yet: np.tile(np.arange(2),(newx.shape[0],newy.shape[0],1)) will give the same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.