tags:

views:

196

answers:

3

Let me illustrate this question with an example:

import numpy

matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant
base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above

result = numpy.array([ base[line] for line in matrix ])

result now holds the desired result, but I'm sure there is a numpy-specific method for doing this that avoids the explicit iteration. What is it?

A: 

Here is another ugly way of doing it:

n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))
saffsd
+1  A: 

If I understand your question correctly you can simply use matrix multiplication:

result = numpy.dot(matrix, base)

If the result must have the same shape as in your example just add a reshape:

result = numpy.dot(matrix, base).reshape((5,1))

If the matrix is not symmetric be careful about the order in dot.

nikow
A: 

My try:

numpy.sum(matrix * base, axis=1)
Roberto Bonvallet