%% Reconstruct Sinusoid from STFT Magnitude
% Consider 512 samples of a sinusoid with a normalized frequency of \pi /60 rad/sample and a DC value of 1. Compute the STFT of the signal.

n = 512;

x = cos(pi/60*(0:n-1)')+1;

S = stft(x);

% Reconstruct the sinusoid from the magnitude of the STFT. Plot the original and reconstructed signals.

xr = stftmag2sig(abs(S),size(S,1));

plot(x)
hold on
plot(xr,'--','LineWidth',2)
hold off
legend('Original','Reconstructed')

%
% Repeat the computation, but now pad the signal with zeros to decrease edge effects.

xz = circshift([x; zeros(n,1)],n/2);

Sz = stft(xz);
xr = stftmag2sig(abs(Sz),size(Sz,1));

xz = xz(n/2+(1:n));
xr = xr(n/2+(1:n));

plot(xz)
hold on
plot(xr,'--','LineWidth',2)
hold off
legend('Original','Reconstructed')

% Repeat the computation, but now decrease edge effects by assuming that x is a segment of a signal twice as long.

xx = cos(pi/60*(-n/2:n/2+n-1)')+1;

Sx = stft(xx);
xr = stftmag2sig(abs(Sx),size(Sx,1));

xx = xx(n/2+(1:n));
xr = xr(n/2+(1:n));

plot(xx)
hold on
plot(xr,'--','LineWidth',2)
hold off
legend('Original','Reconstructed')

% Copyright 2020 The MathWorks, Inc.