MATLAB code (at https://metrw-pitch.blogspot.com/ you can see improved code) executing in MATLAB online R2020b, outputs good accuracy even for low fundamental frequencies (fundFreq) but the code (originally in the answer to a question of mine) for a similar algorithm in C++ (ported in Matlab), executing in Visual Studio 2019, outputs bad accuracy in low (lower than 150 Hz) frequencies.
My question is whether MATLAB's code executing in a dsp kit retains its accuracy.
I'm homeless (in France) and get internet access only at Social Services offices and Post Offices, so it's impossible for me to run code with a dsp kit. Would you please test MATLAB's code in your dsp kits and tell me its output for fundFreq 50, 60 and 70 Hz? Be aware that when changing fundFreq, also change, if necessary, FFTfundFreq and/or GridDemiSpan so that the grid's span covers fundFreq.
I have asked a similar question on 8 Feb 2021 at 13:25, at MATLAB but nobody answered yet.
Copy of Matlab's code without comments is following.
SampFreq = 16000;
Segm = 1:1600;
FundFreq = 50;
FFTfundFreq = 41;
GridDemiSpan = 10;
FirstHarmAngles = FundFreq2pi/SampFreqSegm+1.9pi;
SinFirstHarmAngles = sin(FirstHarmAngles);
SecondHarmAngles = FundFreq22pi/SampFreqSegm+0.9pi;
SinSecondHarmAngles = sin(SecondHarmAngles);
ThirdHarmAngles = FundFreq32pi/SampFreqSegm+0.3pi;
SinThirdHarmAngles = sin(ThirdHarmAngles);
Xn = 170000SinFirstHarmAngles+220000SinSecondHarmAngles+...
150000*SinThirdHarmAngles;
Freqs = FFTfundFreq-GridDemiSpan:0.1:FFTfundFreq+GridDemiSpan;
MagnSqrd = ones(1,201);
for f = 1:201
Angles = Freqs(f)2pi/SampFreqSegm;
XnCos = sum(Xn.cos(Angles));
XnSin = sum(Xn.*-sin(Angles));
MagnSqrd(f) = XnCos.^2+XnSin.^2;
end
[maxMagnSqrd, maxMagnSqrdIndex] = max(MagnSqrd);
GRIDfundFreq = Freqs(maxMagnSqrdIndex);
disp(GRIDfundFreq);
format shortandformat longdo not change the computation, only the display of values at the end. MATLAB always uses double precision float in computation, unless you specifically cast a matrix to typesingle. When generating C code, you can choose betweenfloat(single precision, 32 bit) anddouble(64 bit). – Cris Luengo Aug 20 '22 at 15:53