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?
As the comment points out, you can also use
Array.map2
: