I think this should work for you:
ffty = fft(y);
P2 = abs(ffty/length(ffty));
P1 = P2(1:ceil(length(y)/2));
P1(2:end-1) = 2*P1(2:end-1);
[amp,locs] = findpeaks(P1);
freqs = (locs-1)/t(end);
signal_1=0;
for n=1:length(freqs)
signal_1 = (signal_1+amp(n)*sin(2*pi*freqs(n)*t));
end
hold on;
plot(smooth(signal_1));
plot(y,'b');
Here, P2 is the two-sided spectrum and P1 is the single-sided spectrum.
A two-sided power spectrum displays half the energy at the positive frequency and half the energy at the negative frequency. Therefore, to convert a two-sided spectrum to a single-sided spectrum, you discard the second half of the array and multiply every point except for DC by two.
Also, while regenerating the signal in the "for" loop, you need to take the amplitude of corresponding frequencies into consideration. Hence, you need the first output "amp" of "findpeaks".
You can also eliminate the "for" loop by using vectorization:
signal_1=sum(amp'.*(sin(2*pi*freqs'*t)));
Best Answer