快速线性插值和上采样

时间:2018-11-08 16:54:55

标签: arrays swift interpolation accelerate-framework linear-interpolation

我有一些指标采样不均。我想将这些指标线性插值并上采样到特定的采样频率。我曾尝试使用Accelerate Framework和SIMD框架,但我不确定该怎么做。

问题本身如下:

let original_times:[Double] = [0.0, 2.0, 3.0, 6.0, 10.0]
let original_values: [Double] = [50.0, 20.0, 30.0, 40.0, 10.0]
let new_times:[Double] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

所以我正在寻找一种通过某种线性插值方法查找new_values的方法。

2 个答案:

答案 0 :(得分:3)

vDSP_vgenpD将为您完成这项工作。将原始时间和值传递给它,它将使用插值填充数组。例如:

import Accelerate

let original_times:[Double] =    [0.0,  2.0,  3.0,  6.0, 10.0]
let original_values: [Double] = [50.0, 20.0, 30.0, 40.0, 10.0]

var new_values = [Double](repeating: 0,
                          count: 11)

let stride = vDSP_Stride(1)

vDSP_vgenpD(original_values, stride,
            original_times, stride,
            &new_values, stride,
            vDSP_Length(new_values.count),
            vDSP_Length(original_values.count))

您可以使用以下方法获取时间/值元组数组:

let result = new_values.enumerated().map{ return $0 }

看起来像:

enter image description here

答案 1 :(得分:0)

插值是一个广阔的领域(请参阅Wikipedia:https://en.wikipedia.org/wiki/Interpolation

最简单的方法是像这样的线性插值。

class LinearInterpolation {

private var n : Int
private var x : [Double]
private var y : [Double]
init (x: [Double], y: [Double]) {
    assert(x.count == y.count)
    self.n = x.count-1
    self.x = x
    self.y = y
}

func Interpolate(t: Double) -> Double {
    if t <= x[0] { return y[0] }
    for i in 1...n {
        if t <= x[i] {
            let ans = (t-x[i-1]) * (y[i] - y[i-1]) / (x[i]-x[i-1]) + y[i-1]
            return ans
        }
    }
    return y[n]
}

}

用法:

    let original_times:[Double] = [0.0, 2.0, 3.0, 6.0, 10.0]
    let original_values: [Double] = [50.0, 20.0, 30.0, 40.0, 10.0]
    let new_times:[Double] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
    let ipol = LinearInterpolation(x: original_times, y: original_values)
    for t in new_times {
        let y = ipol.Interpolate(t: t)
        print("t: \(t) y: \(y)")
    }

在用例中,例如音频数据,您应该看一下傅立叶分析。