Equivalent of PWELCH for MATLAB coder
Show older comments
Hello,
I'm trying to generate C code from MATLAB, but one of my functions uses pwelch, which is not supported in C. I was looking how to get the same result with supported functions, but the answers I have found don't match with my problem. Could you please help me with this?
Here's my pWelch:
N=4096;
fs=1000;
[p, f] = pwelch(x,rectwin(length(x)),[],N,fs);
Thank you.
2 Comments
harris harris
on 12 Jan 2021
I'm facing same problem did you manage to solve it ?
Mathieu NOE
on 12 Jan 2021
hello
the function described below is equivalent : split the signal in buffers, apply window , do fft and average
I guess you can rely on some fft C package.
nota : the applied window here is hanning, if you 'd choose another window , you have to change the amplitude correction coefficient
hope it helps
function [freq_vector,fft_spectrum] = myfft_peak(signal, Fs, nfft, Overlap)
% FFT peak spectrum of signal (example sinus amplitude 1 = 0 dB after fft).
% Linear averaging
% signal - input signal,
% Fs - Sampling frequency (Hz).
% nfft - FFT window size
% Overlap - buffer overlap % (between 0 and 0.95)
signal = signal(:);
samples = length(signal);
% fill signal with zeros if its length is lower than nfft
if samples<nfft
s_tmp = zeros(nfft,1);
s_tmp((1:samples)) = signal;
signal = s_tmp;
samples = nfft;
end
% window : hanning
window = hanning(nfft);
window = window(:);
% compute fft with overlap
offset = fix((1-Overlap)*nfft);
spectnum = 1+ fix((samples-nfft)/offset); % Number of windows
% % for info is equivalent to :
% noverlap = Overlap*nfft;
% spectnum = fix((samples-noverlap)/(nfft-noverlap)); % Number of windows
% main loop
fft_spectrum = 0;
for i=1:spectnum
start = (i-1)*offset;
sw = signal((1+start):(start+nfft)).*window;
fft_spectrum = fft_spectrum + (abs(fft(sw))*4/nfft); % X=fft(x.*hanning(N))*4/N; % hanning only
end
fft_spectrum = fft_spectrum/spectnum; % to do linear averaging scaling
% one sidded fft spectrum % Select first half
if rem(nfft,2) % nfft odd
select = (1:(nfft+1)/2)';
else
select = (1:nfft/2+1)';
end
fft_spectrum = fft_spectrum(select);
freq_vector = (select - 1)*Fs/nfft;
end
Answers (0)
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!