I posted the following Matlab script in response to a question on Signal Processing. Here is the questions with my answer.

I am looking for comments on how to make this code more instructive for the questioner. Any other code review comments are also welcomed.

fs = 2^10;        %sample frequency in Hz
T  = 1/fs;        %sample period in s
L  = 2^20;        %signal length
t  = (0:L-1) * T; %time vector

A1 = 0.2; %amplitude of x1 (first signal)
A2 = 1.0; %amplitude of x2 (second signal)
f1 = 1;   %frequency of x1
f2 = 50;  %frequency of x2

x1 = A1*sin(2*pi*f1 * t); %sinusoid 1
x2 = A2*sin(2*pi*f2 * t); %sinusoid 2
y  = x1 + x2;

%Plot signal
set(gcf,'Color','w'); %Make the figure background white
plot(fs*t(1:100), y(1:100));
set(gca,'Box','off'); %Axes on left and bottom only
str = sprintf('Signal with %dHz and %dHz components',f1,f2);
xlabel('time (milliseconds)');

%Calculate spectrum
Y = fft(y)/L;
ampY = 2*abs(Y(1:L/2+1));
f = fs/2*linspace(0,1,L/2+1);
i = L/fs * (max(f1,f2)) + 1; %show only part of the spectrum

%Plot spectrum.
set(gcf,'Color','w');  %Make the figure background white
plot(f(1:i), ampY(1:i));
set(gca,'Box','off');  %Axes on left and bottom only
title('Single-Sided Amplitude Spectrum of y(t)');
xlabel('Frequency (Hz)');
  • 1
    \$\begingroup\$ Y = fft(y)/L Why do you divide by L? \$\endgroup\$
    – user22171
    Feb 15, 2013 at 9:25

1 Answer 1


Your time vector definition is defined a bit strange, I would go for the more standardized form of


endpoint = T*(L-1) % is this correct?

Besides this you could perhaps add some comments in the calculate spectrum section, but for the rest it looks quite clear.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.