Take the tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I need a numpy matrix with comparisons among all elements in a sequence:

from numpy import matrix
seq = [0, 1, 2, 3]
matrix([[cmp(a, b) for a in seq] for b in seq])

I'd like to know if there is a better way to do this.

share|improve this question
 
Useful reference for anyone wanting to take this on: scipy.org/NumPy_for_Matlab_Users –  Alain Jul 6 '12 at 15:02
add comment

1 Answer

up vote 3 down vote accepted

Why are you using matrix rather than array? I recommend sticking with array

As for a better way:

seq = numpy.array([0, 1, 2, 3])
numpy.clip(seq[:,None] - seq, -1, 1)
  1. seq[:, None], moves the numbers into the second dimension of the array
  2. seq[:, None] - seq broadcasts the numbers against each other, and subtracts them.
  3. numpy.clip converts lower/higher values into 1 and -1
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.