compute the frequency spectrum of signal x and plot the magnitude in the frequency range fs{2 ¤ f ¤ fs{2, where fs is the sampling frequency. in matlab

To compute the frequency spectrum of a signal x and plot its magnitude in matlab, we can use the fft function to compute the Discrete Fourier Transform (DFT) of the signal, and then plot the magnitude of the result using the plot function.

Here's the code:

main.m
fs = 1000; % sampling frequency
t = 0:1/fs:1-1/fs; % time vector
x = sin(2*pi*50*t) + sin(2*pi*120*t); % signal

y = fft(x); % DFT of x
f = linspace(-fs/2,fs/2,length(y)); % frequency vector
m = abs(y); % magnitude of DFT

figure;
plot(f,m); % plot magnitude vs frequency
xlabel('Frequency (Hz)');
ylabel('Magnitude');
xlim([-fs/2,fs/2]); % set limits of x-axis
362 chars
14 lines

This code generates a signal x which is the sum of two sinusoids, one at 50 Hz and the other at 120 Hz. The sampling frequency is set to 1000 Hz. We then compute the DFT of x using the fft function, and compute the corresponding frequency vector f using linspace. We also compute the magnitude of the DFT and plot it against the frequency using the plot function. The x-axis limits are set to the range [-fs/2, fs/2] to display the negative and positive frequencies. The resulting plot shows the magnitude of the signal as a function of frequency.

gistlibby LogSnag