How To Apply a Function to an Array of float Arrays?

前端 未结 2 1766
执念已碎
执念已碎 2021-01-15 06:50

Let\'s suppose I have n arrays, where n is a variable (some number greater than 2, usually less than 10).

Each array has k elements.

I also have an array of

相关标签:
2条回答
  • 2021-01-15 07:26

    Something like this did it for me:

    let weights = [|0.6;0.3;0.1|]
    
    let arrs = [| [|0.0453;0.065345;0.07566;1.562;356.6|] ; 
                  [|0.0873;0.075565;0.07666;1.562222;3.66|] ; 
                  [|0.06753;0.075675;0.04566;1.452;3.4556|] |]
    
    let applyWeight x y = x * y
    
    let rotate (arr:'a[][]) = 
        Array.map (fun y -> (Array.map (fun x -> arr.[x].[y])) [|0..arr.Length - 1|]) [|0..arr.[0].Length - 1|]
    
    let weightedarray = Array.map (fun x -> Array.map(applyWeight (fst x)) (snd x)) (Array.zip weights arrs)
    
    let newarrs = Array.map Array.sum (rotate weightedarray)
    
    printfn "%A" newarrs
    

    By the way.. the 0 preceding a float value is necessary.

    0 讨论(0)
  • 2021-01-15 07:28

    Here's one solution:

    let combine weights arrs =
      Array.map2 (fun w -> Array.map ((*) w)) weights arrs 
      |> Array.reduce (Array.map2 (+))
    

    EDIT

    Here's some (much needed) explanation of how this works. Logically, we want to do the following:

    1. Apply each weight to its corresponding row.
    2. Add together the weight-adjusted rows.

    The two lines above do just that.

    1. We use the Array.map2 function to combine corresponding weights and rows; the way that we combine them is to multiply each element in the row by the weight, which is accomplished via the inner Array.map.
    2. Now we have an array of weighted rows and need to add them together. We can do this one step at a time by keeping a running sum, adding each array in turn. The way we sum two arrays pointwise is to use Array.map2 again, using (+) as the function for combining the elements from each. We wrap this in an Array.reduce to apply this addition function to each row in turn, starting with the first row.

    Hopefully this is a reasonably elegant approach to the problem, though the point-free style admittedly makes it a bit tricky to follow. However, note that it's not especially performant; doing in-place updates rather than creating new arrays with each application of map, map2, and reduce would be more efficient. Unfortunately, the standard library doesn't contain nice analogues of these operations which work in-place. It would be relatively easy to create such analogues, though, and they could be used in almost exactly the same way as I've done here.

    0 讨论(0)
提交回复
热议问题