[Numpy-discussion] evaluating a function in a matrix element???

Friedrich Romstedt friedrichromstedt@gmail....
Thu Mar 18 16:31:24 CDT 2010


2010/3/18 Frank Horowitz <frank@horow.net>:
> I'm working on a piece of optimisation code where it turns out to be mathematically convenient to have a matrix where a few pre-chosen elements must be computed at evaluation time for the dot product (i.e. matrix multiplication) of a matrix with a vector.

The following *might* be helpful:

>>> class X:
...     def __mul__(self, other):
...             return numpy.random.random() * other
...     def __rmul__(self, other):
...             return other * numpy.random.random()

Instances of this class calculate the product in-time:

>>> x = X()
>>> x * 1
0.222103712078775
>>> 1 * x
0.044647569053175573

How to use it:

>>> a = numpy.asarray([[X(), X()], [0, 1]])
>>> a
array([[<__main__.X instance at 0x00AABAA8>,
        <__main__.X instance at 0x00E76530>],
       [0, 1]], dtype=object)

The first row is purely random, the second purely deterministic:

>>> numpy.dot(a, [1, 2])
array([1.60154958363, 2], dtype=object)
>>> numpy.dot(a, [1, 2])
array([2.06294335235, 2], dtype=object)

You can convert back to dtype = numpy.float by result.astype(numpy.float):

>>> numpy.dot(a, [1, 2]).astype(numpy.float)
array([ 1.33217562,  2.        ])

Friedrich


More information about the NumPy-Discussion mailing list