Search code examples
swiftaccelerate-frameworkaccelerate

Element-wise maximum value for two arrays with Accelerate


Given two arrays of floats

let A: [Float] = [a1, a2, a3, a4, ...]
let B: [Float] = [b1, b2, b3, b4, ...]

how, with Accelerate can I get an array giving me the maximum value of the two arrays, i.e. how to obtain

let R = [max(a1, b1), max(a2, b2), ...]

Solution

  • vDSP_vmax computes the element-wise maximum of two vectors.

    Starting with macOS 10.15/iOS 13 this is also available as a generic maximum method.

    Example:

    let a: [Float] = [ 1.0, 2.0, 3.0 ]
    let b: [Float] = [ 3.0, 2.0, 1.0 ]
    
    var result: [Float]
    if #available(OSX 10.15, iOS 13.0, *) {
        result = vDSP.maximum(a, b)
    } else {
        result = [ 0.0, 0.0, 0.0 ]
        vDSP_vmax(a, 1, b, 1, &result, 1, 3)
    }
    print(result) // [3.0, 2.0, 3.0]