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?
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 this:
Array.map2 (*) xs ys
Something like
[| for i in 0 .. array_1.Length - 1 ->
array_1.[i] * array_2.[i] |]
should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With