0

I am trying to figure out whether there's a numpy/scipy function to efficiently partition an array into subarrays using a certain rule.

My problem is the following: I have a nxn matrix, lets call it W. And I have a vector h. I now want to partition the column vectors of W into 3 arrays:

  • W_pos, where > 0 for all vectors w from W_pos
  • W_null, where = 0 for all vectors w from W_null
  • W_neg, where < 0 for all vectors w from W_neg

Right now I am doing it like this, which is working but I think it is not very efficient:

    nonzero_indices = (sp.isclose(sp.dot(h_k.T, W),0, 10e-12) == False)
    self.W_null = W[:,~nonzero_indices]

    W_nonzero = W[:,nonzero_indices]
    pos_indices = (sp.dot(h_k.T, W_nonzero) > 0)
    W_pos = W_nonzero[:,pos_indices]
    W_neg = W_nonzero[:,~pos_indices]

Is there a better way? Thanks for your help and if there something not clear please let me know. Cheers

1
  • Where's the inefficiency? Generating the masks, or in indexing? Commented Nov 30, 2015 at 17:05

1 Answer 1

2
w=np.random.random((10,10))-0.5 # example array

.

wneg = w[w<0]

wzero = w[w==0]

wpos = w[w>0]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. How is this faster than my version? In this case I would have to go through the entire array 3 times, once for each partition(pos/neg/zero).
You have to do timings. At this level of coding, reasoning only gets you so far. I suspect indexing takes longer than generating the masks.

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.