Here is the explanation for the lines highlighted in bold.
1. f = fs/2*linspace(0,1,NFFT/2+1);
2. xf = abs(fft(data, NFFT)); Here, abs(fft(data, NFFT)); should be abs(fft(data, NFFT))/l; as the fft result is generally divided by the signal length in order to scale it to the same total power as the time-domain signal.
fft is a method used to transform from the time domain to the frequency domain and gives a complex result. Since, spectrun is the distribution of the amplitudes and phases of each frequency component against frequency, we are using abs function to get the amplitude of each frequency component.
3. plot(f, xf(1:NFFT/2+1)); Here, xf(1:NFFT/2+1) should be 2*xf(1:NFFT/2+1).
To compensate analytically for the notion that no negative frequencies exist, the symmetrical negative frequency components are truncated using xf(1:NFFT/2+1) and the positive frequency components are multiplied by two instead.