Change axis from time to frequency
13 views (last 30 days)
Show older comments
I have this plot:
[x,fs]=audioread('audio.ogg');
x=x(1:round(end/10));
n=0:length(x)-1;
s=cos(2*pi*1.25*n).';
x1=x+0.01*s;
y=abs(fft(x1));
plot(y)
And I want to express the time axis in kHz. How can I implement that on Matlab?
Thank you in advance!
0 Comments
Accepted Answer
Daniel M
on 23 Oct 2019
y is not a time series. Hz are not a unit of time. You cannot express something in the frequency domain as a function of time, because it is not a function of time. (The only thing that might make sense is to plot the magnitude of the fourier transform as a function of the period, which is the inverse of the frequency. But this is trivial, and is still not a time-domain representation of your signal).
Perhaps you mean to plot x in the time domain.
[x,fs]=audioread('audio.ogg');
x=x(1:round(end/10));
t = 0:1/fs:(length(x)-1)/fs; % create a time vector
figure
plot(t,x)
xlabel('Time (s)')
Otherwise, I suggest you read the documentation and examples on fft.
3 Comments
Daniel M
on 24 Oct 2019
Edited: Daniel M
on 24 Oct 2019
It would appear that the frequencies would go from zero up to the sampling frequency, but it does not. fft actually returns the frequencies in the following order: zero, positive frequencies up to the Nyquist frequency (half the sampling frequency), followed by the negative frequencies (ascending). You can see this if you look at the frequency spectrum of a sine wave (with a DC offset), and compare it to the same signal with an fftshift.
So for your case, the following code works. Note I'm only taking the positive side of the frequency spectrum, because that is what is physically interpretable.
clear; clc; close all;
load handel
% x = y(1:round(end/10));
x = y;
n = 0:length(x)-1;
t = 0:1/Fs:(length(x)-1)/Fs;
s = cos(2*pi*1.25*n).';
s = cos(2*pi*1.25*t).';
x1 = detrend(x+0.01*s);
figure
plot(x1)
xlabel('Time [s]')
ylabel('Magnitude')
X = abs(fft(x1));
L = length(X);
% just take positives frequencies
f = Fs*(0:floor(L/2))/L;
X2 = X(1:floor(L/2)+1);
figure
plot(f,X2);
xlabel('Frequency [Hz]')
ylabel('Magnitude')
title('Single sided amplitude spectrum')
More Answers (0)
See Also
Categories
Find more on Get Started with Signal Processing Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!