how to get a spectrum from data in matlab

To get a spectrum from data in Matlab, you can use the fast Fourier transform (FFT) algorithm. Here is an example code to illustrate how to do it:

main.m
% Generate a sample signal
fs = 1000; % Sampling rate
t = 0:1/fs:1-1/fs; % Time axis
f = 10; % Signal frequency
x = cos(2*pi*f*t); % Signal

% Compute the one-sided spectrum
N = length(x); % Signal length
X = fft(x)/N; % FFT and normalization
faxis = (0:N-1)*(fs/N); % Frequency axis
X_one_sided = X(1:N/2+1); % Keep the one-sided spectrum
faxis_one_sided = faxis(1:N/2+1);

% Plot the spectrum
figure;
stem(faxis_one_sided,abs(X_one_sided),'LineWidth',1);
title('One-Sided Amplitude Spectrum of x(t)');
xlabel('Frequency (Hz)');
ylabel('Amplitude');
grid on;
560 chars
21 lines

In this code, we first generate a sample signal x that consists of a cosine waveform with a frequency of 10 Hz. Then, we apply the FFT algorithm to x and normalize the result by dividing by the signal length N. We also compute the frequency axis faxis. Since the output of the FFT algorithm is a double-sided spectrum, we only keep the one-sided part of the spectrum X_one_sided, which corresponds to frequencies from 0 to the Nyquist frequency (fs/2). Finally, we plot the one-sided amplitude spectrum using the stem function.

gistlibby LogSnag