Re: Can I Mapthis code?
- To: mathgroup at smc.vnet.net
- Subject: [mg95971] Re: Can I Mapthis code?
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sat, 31 Jan 2009 01:13:21 -0500 (EST)
On 1/30/09 at 5:42 AM, aagas at ix.netcom.com (Andreas) wrote: >As I have more experience with procedural programming, I'd like to >better understand how to use Mathematica's capabilities to do >operations to or mapping functions to lists. >As an example I have two lists of lists: >values = {{1, 1, 1, 1}, {1.03, 1.01, .90, .87}, {1.15, .987, 1.1, >1}, {.925, 1.1, 1.03, 1}} >points = { {0.0842331, 0.445974, 0.0762394, 0.393553}, {0.0507857, >0.316297, 0.217557, 0.415361}, {0.0772796, 0.715707, 0.0966355, >0.110378}, {0.407287, 0.0992621, 0.294046, 0.199405}, {0.115973, >0.483231, 0.125979, 0.274817}, {0.0819106, 0.64151, 0.0656714, >0.210908}, {0.0240671, 0.164786, 0.230353, 0.580795}, {0.0402821, >0.582524, 0.131371, 0.245823}, {0.374207, 0.242838, 0.0277256, >0.355229}, {0.130812, 0.459584, 0.331101, 0.078503} >} >I have a named function: >function2[point_, value_] := If[value == 0, 0, 1 + ((value - 1) * >point)] >That I want to apply across the elements in the list in a function >like the following: >function1[points_, values_] := >Table[ Sum[ Sum[ function2[points[[j, k]], values[[i, k]]], {k, 1, >Length[values[[1]]]} >], {j, 1, Length[points]} >]/Length[points], >{i, 1, Length[values]} >] >function1 works OK. I just wonder if I can do this kind of >calculation more elegantly using something like the Map[] function >and how I would do it in a situation like the above. >I also have a concern about processing speed as the lengths of both >lists of lists can get quite large. =46irst I would re-write function2 so that it operates on lists rather than individual points. That is I would write function2 as: f[pointArray_, valueList_] := Unitize[valueList] (1 + (valueList - 1) #) & /@ pointArray Unitize[x] returns 1 if x isn't 0 and 0 otherwise Now, the desired answer can be obtained as: In[2]:= (Total[f[points, #], 2] & /@ values)/Length[points] Out[2]= {4,3.9551,4.03137,4.03591} >The larger question goes to this. In what kind of situations should >one use iterative functions like Table[], Sum[], etc and when does >one better use Map[] or other such functions? What advantages and >disadvantages does either approach have over the other? As a general rule, I use things like Sum or Table when I have an expression that needs to be evaluated at specific intervals, not to index an existing list of values. To me the key advantage of this approach is I don't need to worry about the lengths of arrays. One less thing for me to get wrong in code. Also, the resulting code is generally easier to read and understand without specific indexing. The other rule of thumb in Mathematica is best performance is achieved when using functions that are more specific to the task at hand. So, I expect Total to be faster at computing the desired sum than anything using specific indexing.