I need to multiply an array by another array element-wise, just like the Hadamard product of vectors in math. For example:
A = [1,2,3,4]
B = [2,3,4,5]
C = A*B = [2,6,12,20]
I can't even figure out the code, I've tried doing so element by element but this seems too messy of a solution for me, any ideas?
Accelerate framework
For the topic of vector multiplication, another alternative (in addition to the neat
simd
covered by @appzYourLife's answer) is making use of the Accelerate framework. In this case, specifically the vDSP methodsvDSP_vmul
andvDSP_vmuld
,E.g., the latter used for element-by-element multiplication of two vectors of
Double
values:Note that using Accelerate is not as user friendly and safe as the alternative methods, as the vector arguments to
vDSP_vmulD
are captured as unsafe pointers (UnsafePointer<Double>
), and that it's our responsibility to make sure that the input vectors are of same length, as well as the result vector being properly allocated prior to the vector multiplication byvDSP_vmulD
."Zipping" the two arrays gives a sequence of tuples
(a_i, b_i)
which can then be multiplied element-wise:(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:With Swift 5, you can use one of the following ways in order to solve you problem.
#1. Using SIMD vector types
The following Playground sample code shows an element-wise multiplication using
SIMD4
:Note that
SIMD
protocol conforms toExpressibleByArrayLiteral
. Therefore, you can initialize your vector using an array literal:#2. Using a custom type that conforms to
Numeric
andExpressibleByArrayLiteral
protocolsYou can build your own custom type that conforms to
Numeric
andExpressibleByArrayLiteral
. The following Playground sample code shows how to implement and use it:Usage:
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
you can multiply each component