How to multiply two arrays element-wise

Solution 1:

"Zipping" the two arrays gives a sequence of tuples (a_i, b_i) which can then be multiplied element-wise:

let A = [1,2,3,4]
let B = [2,3,4,5]

let C = zip(A, B).map { $0 * $1 }

print(C) // [2, 6, 12, 20]

(If the arrays have different length then zip silently ignores the extra elements of the longer array.)

As @appzYourLife correctly said, you can also pass the multiplication operator directly as an argument to map instead of a closure expression:

let C = zip(A, B).map(*)

Solution 2:

Single Instruction Multiple Data

If your vectors have exactly 4 components you can use the superfast simd (Single Instruction Multiple Data) instructions provided by iOS.

It uses the CPU to perform parallel computations.

Given 2 vectors of 4 components of Int32

import simd

let a = int4(1, 2, 3, 4)
let b = int4(2, 3, 4, 5)

you can multiply each component

let res = a &* b // int4(2, 6, 12, 20)

As noted by Martin R , array of float(s) or of double(s) are provided as well by the simd module.