On Wed, Nov 19, 2008 at 12:19 PM, Jason Grout
<[EMAIL PROTECTED]> wrote:
>
> Stan Schymanski wrote:
>> Hi Mike and Jason,
>>
>> Thanks a lot for the quick response. My problem becomes a bit more
>> obvious if I have a function of several variables. Then the map
>> function becomes somehow impractical because I can't define which list
>> is used for which variable. List comprehensions also get a lot more
>> difficult. Example:
>>
>> sage: var('a b c')
>> sage: f = a*x^2+b
>> sage: w = [4,5,6]
>> sage: z = [7,8,9]
>> sage: map(f,v,w,z)
>> [53, 133, 249]
>> sage: map(f,w,v,z)
>> [197, 322, 489]
>>
>> I wouldn't even know how to do this with a list comprehension in one
>> step. Since the functions I work with have to be applied to time
>> series of quite a few variables, I am really desperate for a practical
>> way of doing this. So far, all mathematical programs I worked with
>> were able to do this and I bet that many people are used to applying
>> functions to lists and arrays. Isn't this a lot faster than defining
>> loops?
>
>
> I would generally use list comprehensions over map.  So, you could do:
>
> sage: [f(a=i,x=j,b=k) for i,j,k in zip(v,w,z)]

Or just

sage: f = lambda x: x[1]*x[0]^2+x[2]
sage: v = [1,2,3]
sage: w = [4,5,6]
sage: z = [7,8,9]
sage: map(f,zip(v,w,z))
[11, 28, 63]


>
> Note that numpy has the concept of "universal functions" which
> automatically thread over a list, much like Matlab would.
>
> sage: np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
>
> Also, if you want threadable functions, you can do it easily with pure
> python functions and a decorator:
>
> def threadable(f):
>     def threadable_f(*args,**kwds):
>         return [f(*tuple, **kwds) for tuple in zip(*args)]
>     return threadable_f
>
> @threadable
> def f(x,y,z):
>     return x*y^2+z
>
> f([1,2,3],[4,5,6],[7,8,9])
>
>
> This last call produces:
>
> [23, 58, 117]
>
>
> Jason
>
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to