Compute the power spectrum of the input vector ( pspectrum()) and its code generation

5 views (last 30 days)
Hi, I want to generate a function for calculating the power spectrum of the input. Then generating C code using matlab coder. However, the output are always not equal to the simulated ones.
function pwr_sptrume = Spectrum(dat_input)
pwr_sptrume = pspectrum(dat_input,80000000,'FrequencyLimits',[200000, 4000000]);
end
dat_input is 1000x1 vector, and the simulated and the generated code's results pwr_sptrume are all 4096x1.
but the two 4096x1 vector are totall different. In other words, the verified code get wrong result during code generation.
My question is why cannot generate correct power spectrum of the input using matlab coder?

Answers (1)

Sumukh
Sumukh on 5 Sep 2024
Hi Audo,
MATLAB Coder creates a .mex file from the generated C code for a given function. The .mex file can be used to check the validity of the generated C code with the MATLAB code. The results obtained are not equal to the last decimal digit due to precision loss when converted to C, but the difference is negligible. You can refer to the following documentation to know more about the differences in results between MATLAB Code and Generated C code:
I have tested the function provided as well as the generated .mex file (file attached) with a random input vector of size 1000x1, and the results do match. You can run the following code to compare the outputs:
figure;
input=sin(randi([0 50],1000,1)); % Random input of size 1000x1
y= Spectrum(input); % Output from MATLAB function
y1 = Spectrum_mex(input); % Output from MEX file (.mex file attached)
% Plotting outputs:
plot(y,"--r","LineWidth",3);
hold on;
plot(y1,"-.b","LineWidth",4);
hold off;
legend("Output from MATLAB Code","Output from generated C code");
I hope this helps with the issue.

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!