\$\begingroup\$
\$\endgroup\$
1
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.
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 5, 2012 at 17:22
-
\$\begingroup\$ Useful reference for anyone wanting to take this on: scipy.org/NumPy_for_Matlab_Users \$\endgroup\$Alain– Alain2012年07月06日 15:02:56 +00:00Commented Jul 6, 2012 at 15:02
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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)
seq[:, None]
, moves the numbers into the second dimension of the arrayseq[:, None] - seq
broadcasts the numbers against each other, and subtracts them.numpy.clip
converts lower/higher values into 1 and -1
answered Jul 6, 2012 at 15:06
lang-py