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.
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.Sign up to join this community
Why are you using
matrix rather than
array? I recommend sticking with
As for a better way:
seq = numpy.array([0, 1, 2, 3]) numpy.clip(seq[:,None] - seq, -1, 1)
seq[:, None], moves the numbers into the second dimension of the array
seq[:, None] - seqbroadcasts the numbers against each other, and subtracts them.
numpy.clipconverts lower/higher values into 1 and -1