%% Short-Time Fourier Transform of Sinusoid
% Generate a 3 × 160 (× 1) array containing one batch of a three-channel, 160-sample sinusoidal signal. The normalized sinusoid frequencies are π/4 rad/sample, π/2 rad/sample, and 3π/4 rad/sample. Save the signal as a dlarray, specifying the dimensions in order. dlarray permutes the array dimensions to the "CBT" shape expected by a deep learning network.

nch = 3;
N = 160;
x = dlarray(cos(pi.*(1:nch)'/4*(0:N-1)),"CTB");

%
% Create a short-time Fourier transform layer that can be used with the sinusoid. Specify a 64-sample rectangular window, 48 samples of overlap between adjoining windows, and 1024 DFT points. Specify the layer output mode as "spatial". By default, the layer outputs the magnitude of the STFT.

stfl = stftLayer(Window=rectwin(64), ...
    OverlapLength=48, ...
    FFTLength=1024, ...
    OutputMode="spatial");

% Create a two-layer dlnetwork object containing a sequence input layer and the STFT layer you just created. Treat each channel of the sinusoid as a feature. Specify the signal length as the minimum sequence length for the input layer.

layers = [sequenceInputLayer(nch,MinLength=N) stfl];
dlnet = dlnetwork(layers);

%
% Run the sinusoid through the forward method of the network.

dataout = forward(dlnet,x);

% Convert the network output to a numeric array. Use the squeeze function to collapse the size-1 batch dimension. Plot the STFT magnitude separately for each channel in a waterfall plot.

q = squeeze(extractdata(dataout));

for kj = 1:nch
    subplot(nch,1,kj)
    waterfall(q(:,:,kj)')
    view(30,45)
    zlabel("Ch. "+string(kj))
end

% Copyright 2020 The MathWorks, Inc.