Swift中的DFT结果与MATLAB的结果不同

时间:2017-01-07 09:04:03

标签: swift matlab fft accelerate-framework vdsp

import Cocoa
import Accelerate

let filePath = Bundle.main.path(forResource: "sinusoid", ofType: "txt")
let contentData = FileManager.default.contents(atPath: filePath!)
var content = NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String

var idx = content?.characters.index(of: "\n")
idx = content?.index(after: idx!)

repeat {
    //let fromIndex = index(from: )
    content = content?.substring(from: idx!)
    idx = content?.characters.index(of: "\n")
    idx = content?.index(after: idx!)
} while content!.characters.contains("%")

let regex = try? NSRegularExpression(pattern: "[ ]+", options:[])

let delimiter = ","
var modifiedString = regex?.stringByReplacingMatches(in: content!, options: [], range: NSRange(location: 0, length: (content! as NSString).length), withTemplate: delimiter)

let lines = modifiedString?.components(separatedBy: "\n")

var s = [Double]()

for var line in lines! {
    if !line.isEmpty {
        let data = line.components(separatedBy: ",")
        s.append(Double(data[1])!)
    }
}

let length = vDSP_Length(pow(2, floor(log2(Float(s.count)))))
let L = Int(length)

// zrop or zop? 
// zrop covers real to complex, and zop covers complex
// length must be a power of 2 or specific multiples of powers of 2 if size is at least 4
let setup = vDSP_DFT_zrop_CreateSetupD(nil, length, vDSP_DFT_Direction.FORWARD)

var inputReal = UnsafeMutablePointer<Double>.allocate(capacity: L)
var inputImaginary = UnsafeMutablePointer<Double>.allocate(capacity: L)
var outputReal = UnsafeMutablePointer<Double>.allocate(capacity: L)
var outputImaginary = UnsafeMutablePointer<Double>.allocate(capacity: L)

for i in 0..<L {
    inputReal[i] = s[i]
    inputImaginary[i] = 0.0
}

vDSP_DFT_ExecuteD(setup!, inputReal, inputImaginary, outputReal, outputImaginary)

for i in 0..<L {
    print("\(outputReal[i]) + \(outputImaginary[i])i")
}

输入文件&#34; sinusoid.txt&#34;在以下链接中 https://dpaste.de/M1VD

输入文件数据由两个频率为50和120的正弦波组成.Matlab代码生成以下链接中给出的正确输出:

https://dpaste.de/2mdK

当Matlab的结果被缩放并且采用幅度时,它正确地表明频率为50的幅度为0.7,频率为120的幅度为1.

clear all; close all; clc;
data = load('sinusoid.txt');
S = data(:,2);
Fs = 1000;
Y = fft(S);
L = length(S);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(L/2))/L;
plot(f,P1)
title('Single-Sided Amplitude Spectrum of X(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')

与Matlab输出相比,Swift代码输出完全不同且无法识别,无论应用何种缩放因子以及是否应用了实数到复数或复数到复数的转换:

https://dpaste.de/MUwB

为什么会这样?

2 个答案:

答案 0 :(得分:1)

2 FFT的长度不同,因此,结果当然不匹配。您还将不同数量的数据传递给2个FFT。

打印FFT长度和输入数据向量以调试代码。在比较结果之前确保输入匹配。

此外,Apple的Accelerate / vDSP FFT可以使用除2的幂之外的长度(也允许使用3或5倍的长度)。

另外,请注意,Matlab将数组从1开始索引,而不是0,这在C和Swift函数中更为典型。

答案 1 :(得分:0)

实际上,FFT结果不匹配的问题是由于输入尺寸不匹配造成的。将输入限制为2的特定倍数大大限制了Accelerate框架中的FFT使用。一个建议是用0填充输入,直到它具有适当的长度。无论是填0还是截断输入,使得大小是2的幂的特定倍数,Accelerate框架的结果将与MATLAB等程序的结果不同。对此的解决方案是执行由Martin R指定的链接中提到的chirp-z变换.chirp-z变换本身产生与FFT相同的结果,并且可以在任意大小的输入上执行。