Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementwise multiplication of arrays in F#

Is there a simple way to multiply the items of an array in F#?

So for example of I want to calculate a population mean from samples I would multiply observed values by frequency and then divide by the sample numbers.

     let array_1 = [|1;32;9;5;6|];;

     let denominator = Array.sum(array_1);;


     denominator;;

     let array_2 = [|1;2;3;4;5|];;

     let productArray = [| for x in array_1 do
                             for y in array_2 do
                                 yield x*y |];;


     productArray;;

     let numerator = Array.sum(productArray);;

     numerator/denominator;;

Unfortunately this is yielding a product array like this:-

     val it : int [] =
     [|1; 2; 3; 4; 5; 32; 64; 96; 128; 160; 9; 18; 27; 36; 45; 5; 10; 15; 20; 25;
        6; 12; 18; 24; 30|]

Which is the product of everything with everything, whereas I am after the dot product (x.[i]*y.[i] for each i).

Unfortunately adding an i variable and an index to the for loops does not seem to work.

What is the best solution to use here?

like image 287
Simon Hayward Avatar asked Oct 17 '12 14:10

Simon Hayward


3 Answers

Array.zip array_1 array_2
    |> Array.map (fun (x,y) -> x * y)

As the comment points out, you can also use Array.map2:

Array.map2 (*) array_1 array_2
like image 65
Lee Avatar answered Nov 03 '22 02:11

Lee


Like this:

Array.map2 (*) xs ys
like image 36
J D Avatar answered Nov 03 '22 01:11

J D


Something like

[| for i in 0 .. array_1.Length - 1 ->
    array_1.[i] * array_2.[i] |]

should work.

like image 3
kvb Avatar answered Nov 03 '22 02:11

kvb