Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
figure;
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);
title(str);
xlabel('time (milliseconds)');
ylabel('Amplitude');

%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.
figure;
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)');
ylabel('|Y(f)|');
share|improve this question
    
Y = fft(y)/L Why do you divide by L? –  user22171 Feb 15 '13 at 9:25

1 Answer 1

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

startpoint:stepsize:endpoint

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

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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