Find value of frequency form Sin wav - matlab

i have a this following equation of sine wav
Fs = 8000; % Sampling rate of signal
Fc = 3000; % Carrier frequency
t = [0:Fs-1]'/Fs; % Sampling times
dev = 50; % Frequency deviation in modulated signal
s1 = sin(2*pi*200*t)+2*sin(2*pi*f*t);
now i want to value of f for s1 equation how can we get this? thanks

You may want to look around SO for similar questions.
The FFT is the simplest route to a solution:
spec = abs(fft(s1));
Then search for the maxima in the spectrum using a detection threshold.
Example (here f=10):
f= 10;
s1 = sin(2*pi*200*t)+2*sin(2*pi*f*t);
thresh = 0.2;
f1=abs(fft(s1))/sum(abs(s1));
f= [0:length(f1)-1]/length(f1)*Fs;
f(f1(1:end/2)>0.2)
This is the result (the frequencies in the spectrum for peaks with amplitude greater than the threshold value):
ans =
10 200

Related

Scaling amplitudes by two for the FFT in MATLAB

I just read the example of Mablab tutorial, trying to studying the FFT function.
Can anyone tell me that for the final step, why P1(2:end-1) = 2*P1(2:end-1). In my opinion, it is not necessary to multiply by 2.
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
%--------
S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
%---------
X = S + 2*randn(size(t));
%---------
plot(1000*t(1:50),X(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('t (milliseconds)')
ylabel('X(t)')
Y = fft(X);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(L/2))/L;
plot(f,P1)
title('Single-Sided Amplitude Spectrum of X(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')
Y = fft(S);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
plot(f,P1)
title('Single-Sided Amplitude Spectrum of S(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')
Matlab sample
The reason for the multiplication by 2 is that the spectrum returned by fft is symmetric about the DC component. Since they are showing the single-sided amplitude spectrum, the amplitude of each point is going to be doubled to account for the contributions of data on the other side of the spectrum. For example, the single-sided amplitude of pi/4 is the amplitude at pi/4 plus the amplitude at -pi/4.
The first sample is skipped since it is the DC point and therefore shared between the two sides of the spectrum.
So for example, if we look at the fft of their example signal with a 50Hz sinusoid of amplitude 0.7 and a 120Hz sinusoid of amplitude 1.
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
% Compute the FFT
Y = fft(S);
% Compute the amplitudes
amplitude = abs(Y / L);
% Figure out the corresponding frequencies
f = Fs/L*[0:(L/2-1),-L/2:-1]
% Plot the result
plot(f, amplitude)
When we plot this, you'll see that it's symmetric and the original input amplitude is only realized by combining the amplitudes from both sides of the spectrum.
A slightly more explicit version of what they have done would be to be the following which sums the two halves of the spectrum
P1(2:end-1) = P1(2:end-1) + P2((L/2+2):end);
But since by definition the spectrum is symmetric, the opt to simply multiply by 2.

Designing a narrow bandpass filter in MATLAB

I'm working on signal filtering in MATLAB. I wrote a signal with 3 different frequencies:
Fs = 8000; %// Sampling frequency
T = 1/Fs; %// Sample time
L = 16000; %// Length of signal
t = (0:L-1)*T; %// Time vector
y = 40*sin(2*pi*50*t) + 500*sin(2*pi*51*t) + 500*sin(2*pi*49*t);
Now I want to extract the 50Hz signal by bandpass window filtering using a Hanning window. Here is my code to design the filter:
function Hd = HannFilter1
Fs = 8000; %// Sampling Frequency
N = 4096; %// Order
Fc1 = 49.5; %// First Cutoff Frequency
Fc2 = 50.5; %// Second Cutoff Frequency
flag = 'scale'; %// Sampling Flag
win = hann(N+1);
b = fir1(N, [Fc1 Fc2]/(Fs/2), 'bandpass', win, flag);
Hd = dfilt.dffir(b);
After that, I do filtering using filter like this:
yfilter = filter(Hd.Numerator,1,y);
NFFT = 2^nextpow2(L);
Y = fft(yfilter,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
figure;
subplot(2,1,1);
plot(yfilter);
subplot(2,1,2);
plot(f,2*abs(Y(1:NFFT/2+1)))
Why is this filter unable to extract the 50Hz signal?
I'm doing something wrong in this simulation?
How can I filter out the 50Hz signal?
what is the best sample rate for 50Hz signal? and very important question! in real world, like balancing system, the main signal is about 20Hz and environment is very too noisy and filtering by my solution does not give a correct answer. in this case,how can i use or choose the best filtering algorithm?
if my sample rate be 8000Hz and I can buffered only 20000 samples, how can Designing a narrow bandpass filter?
So, I Solve problem by decrease sample rate and increase sample data by this code: ( as Matt was Said )
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 60000; % Length of signal
t = (0:L-1)*T; % Time vector
for j=1:20
r1 = 5 + (1000-5).*rand(1,1);
r2 = 5 + (1000-5).*rand(1,1);
y = 10*sin(2*pi*14.8*t) + r1*sin(2*pi*14.2*t) + r2*sin(2*pi*15.5*t) + 1.1*rand(size(t));
yfilter = filter(Hd.Numerator,1,y);
max(yfilter(40000:50000))
end
my filter is KAISER ( FIR Badpass filter ) :
Fs = 1000; % Sampling Frequency
Fstop1 = 14.2; % First Stopband Frequency
Fpass1 = 14.6; % First Passband Frequency
Fpass2 = 15; % Second Passband Frequency
Fstop2 = 15.2; % Second Stopband Frequency
Dstop1 = 1e-06; % First Stopband Attenuation
Dpass = 0.057501127785; % Passband Ripple
Dstop2 = 1e-06; % Second Stopband Attenuation
flag = 'scale'; % Sampling Flag
% Calculate the order from the parameters using KAISERORD.
[N,Wn,BETA,TYPE] = kaiserord([Fstop1 Fpass1 Fpass2 Fstop2]/(Fs/2), [0 ...
1 0], [Dstop1 Dpass Dstop2]);
% Calculate the coefficients using the FIR1 function.
b = fir1(N, Wn, TYPE, kaiser(N+1, BETA), flag);
Hd = dfilt.dffir(b);
and filter amplitude for 20 iteration and random noise signal is :
max(yfilter(40000:50000))
10.01
10.02
10.01
10.00
10.01
10.03
10.01
10.02
....
that is a great result for me, and filtered signal is :
but there is some problem :
1- my sample data length is 60000 bytes, in other hand by sampling rate at 1000Hz, I wait for 60 Seconds for gathering data, and that is too long time!!!
when i decrease sample data length to about 3000 samples, filtered result is so bad because of number of filter's coefficients is about 4097.
how can i filter my signal when it's length is 3000 samples and my filter's coefficients is about 4097 bytes? when i decrease filter's coefficients , filtered signal result is so noisy.
2- what is the best sample rate fo 15 Hz signal?
thanks.

Getting the Period in an audio file

I have an audio file , which represent the sound of a motor running at 2500rpm my aim is to get the period of this signal, so I can automaticlly tell what is the motor speed is. To do that I take a part of the signal and run get it autocorrelation , hopping that this willl tell the period of the singal! but I just don't get it :
here is a part of my code :
clear;
clc;
[x0,Fs] = audioread('_2500.wav');
x= x0(1:2000,1);
xc = xcorr(x);
clf;
subplot(3,1,1);
plot(x);
subplot(3,1,2);
plot(xc);
[peaks,locs] = findpeaks(xc);
hold on
subplot(3,1,3)
plot(xc(locs),'ro');
and here are the plot :
and how should I consider the sampling frequency, which is : 44100 ?
You can use the autocorrelation or FFT of the signal to find where is the maximum:
% Parameters
Fc = 1e1;
Fs = 1e3;
% Signal
t = 0:1/Fs:1;
x = sin(2*pi*Fc*t);
% FFT
Y = abs(fft(x));
[~,I] = max(Y(1:floor(end/2)));
% Frequency and period
F = I-1;
T = 1/F;
% Plot
figure;
subplot(2,1,1); plot(t,x);
subplot(2,1,2); plot(Y);
disp(['The frequency is ',mat2str(F),'Hz, and the period is ',mat2str(T),'sec.']);
This and this post are related.
To go from your auto-correlation function xc to an estimate of the fundamental frequency, do:
fs = 44100; % Unit: Hz
xc = xc((length(xc) - 1) / 2 + 1: end); % Get the half on the positive time axis.
[~, pidx] = findpeaks(xc);
period = (pidx(1) - 1) / fs;
F0 = 1 / period; % Estimated fundamental frequency.
Note that there are other potentially more robust fundamental frequency / pitch estimation algorithms. Doing a google scholar search on "fundamental frequency estimation" or "pitch estimation" will lead you to some good reviews.
you find all peaks using "findpeaks" funciton, now compute the difference between each peak
P=diff(locs)
your period can be :
max(P)
The peiod of 250hz sine at 22050 sample rate, is about 88, the Frequency of your signal is equivalent at the Period if you do (Fs/Period) == Frequency
If you Know the frequency of your signal you can find the period just do Fs/Frequency

A harmonic's amplitude is greater than the fundamental one

Im writing a MATLAB code to detect frequencies in piano recording.
I used a C scale audio file that i recorded using my keyboard (C4 D4 E4 F4 G4 A4 B4 C5)
When i simply perform an FFT (without breaking into windows) then the fundamental frequencies have a higher amplitude which is perfectly fine.
However to be more accurate i did the following steps
1. Did a fast convolution of my audio signal with a Gaussian edge detection filter to obtain the envelope.
2. Implemented a peak detecting algorithm to find the note onsets.
3. Taking each Onset, i performed an FFT on each, so as to get the FFT of each note.
However, when i do this for the above mentioned audio file, i get wrong results, at times the harmonics have a higher amplitude than the 1st.
clear all;
clear max;
clc;
%% create 5s sample at 10kHz with tone from 1s to 2s
FS = 10000; % 10kHz
N=5*FS;
song = randn(N,2)/10;
song(FS:2*FS,:)=10*repmat(sin(261*pi*2*(0:FS)/FS)',1,2)+song(FS:2*FS,:);
P = 2000;
t=0:1/FS:(N-1)/FS; % define time period
song = sum(song,2);
song=abs(song);
%----------------------Finding the envelope of the signal-----------------%
% Gaussian Filter
x = linspace( -1, 1, P); % create a vector of P values between -1 and 1 inclusive
sigma = 0.335; % standard deviation used in Gaussian formula
myFilter = -x .* exp( -(x.^2)/(2*sigma.^2)); % compute first derivative, but leave constants out
myFilter = myFilter / sum( abs( myFilter ) ); % normalize
% fft convolution
myFilter = myFilter(:); % create a column vector
song(length(song)+length(myFilter)-1) = 0; %zero pad song
myFilter(length(song)) = 0; %zero pad myFilter
edges =ifft(fft(song).*fft(myFilter));
tedges=edges(P:N+P-1); % shift by P/2 so peaks line up w/ edges
tedges=tedges/max(abs(tedges)); % normalize
%---------------------------Onset Detection-------------------------------%
% This section does the peak picking algorithm
max_col = maxtab(:,1);
peaks_det = max_col/FS;
No_of_peaks = length(peaks_det);
%---------------------------Performing FFT--------------------------------
song_seg = song(max_col(1):max_col(2)-1);
L = length(song_seg);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
seg_fft = fft(song_seg,NFFT);%/L;
f = FS/2*linspace(0,1,NFFT/2+1);
seg_fft2 = 2*abs(seg_fft(1:NFFT/2+1));
L5 = length(song_seg);
fmin = 60;
fmax = 1000;
region_of_interest = fmax>f & f>fmin;
froi = f(region_of_interest);
[p_max,loc] = max(seg_fft2(region_of_interest));
% index into froi to find the frequency of the peaks
p_max;
f_p_max = froi(loc);
[points, locatn] = findpeaks(seg_fft2(region_of_interest));
aboveMax = points > 0.4*p_max;
if any(aboveMax)
peak_points = points(aboveMax)
f_peak = froi(locatn(aboveMax))
end
end
What am I doing wrong here??? Really REALLY in need of some help here......
It can be seen that the f0 of D4 hasn't been detected at all, while the f0 of C4 and E4 have less amplitudes compared to their harmonics
Using the FFT, i found out the peak in the Frequency Domain. This may correspond to the fundamental note, if we are very lucky. Else, this may be the 1st harmonic generally.
I do not know whether the peak is at the fundamental or at the 1st harmonic.
My job is to find this out.
What i did was...
I have the "max_user_freq" variable that corresponds to the frequency at which the peak occurs in the FFT.
Note: "Spectrum[]" is the magnitude spec variable.
I calculate the maximum of the spectrum[m] where m ranges from frequency
Note : frequencies must be scaled to m. In my case : m=freq*length(fraw)/22050;
Complete Code:
f1=(max_freq/2)-0.05*max_freq;
f1=round(f1);
f2=(max_freq/2)+0.05*max_freq;
f2=round(f2);
m=[];
spec_index_fund_note=m;
spec_fund_max=spectrum(f1*length(fraw)/22050;
for m=f1:f2
spec_index_fund_note(m)=m*length(fraw)/22050;
if(spectrum(spec_index_fund_note(m))>spec_fund_max)
spec_fund_max=spectrum(spec_index_fund_note(m));
end
end
if((spectrum(max_freq_index)-specval_fund_note)/spectrum(max_freq_index)>)
display('1st Harmonic exceeds the fundamental, Retry');
end
Filtering abs(song) is fine for finding the envelope, but when it comes to finding the peaks you need to compute the fft the original signal (without the "abs").
To see the difference, try:
clear;
FS = 10000;
s=sin(261*pi*2*(0:FS)/FS);
NFFT = 2^nextpow2(length(s));
S1=fft(s,NFFT);
S2=fft(abs(s),NFFT);
f = FS/2*linspace(0,1,NFFT/2+1);
plot(f,abs(S1(1:NFFT/2+1))); % peak near 261
plot(f,abs(S2(1:NFFT/2+1))); % peak near 522
I code in matlab and develop applications that are useful for a Musician. I myself am a musician. So, i know the music theory t hat runs my algorithms.
I developed and algorithm in matlab that tells u the exact scale in which u are playing the piano. Have a Look
MATLAB MUSICIAN's BLOG

MATLAB - Using fm demod to decode data

I am trying to extract a sinusoid which itself has a speed which changes sinusiodially. The form of this is approximately sin (a(sin(b*t))), a+b are constant.
This is what I'm currently trying, however it doesnt give me a nice sin graph as I hope for.
Fs = 100; % Sampling rate of signal
Fc = 2*pi; % Carrier frequency
t = [0:(20*(Fs-1))]'/Fs; % Sampling times
s1 = sin(11*sin(t)); % Channel 1, this generates the signal
x = [s1];
dev = 50; % Frequency deviation in modulated signal
z = fmdemod(x,Fc,Fs,fm); % Demodulate both channels.
plot(z);
Thank you for your help.
There is a bug in your code, instead of:
z = fmdemod(x,Fc,Fs,fm);
You should have:
z = fmdemod(x,Fc,Fs,dev);
Also to see a nice sine graph you need to plot s1.
It looks like you are not creating a FM signal that is modulated correctly, so you can not demodulate it correctly as well using fmdemod. Here is an example that does it correctly:
Fs = 8000; % Sampling rate of signal
Fc = 3000; % Carrier frequency
t = [0:Fs]'/Fs; % Sampling times
s1 = sin(2*pi*300*t)+2*sin(2*pi*600*t); % Channel 1
s2 = sin(2*pi*150*t)+2*sin(2*pi*900*t); % Channel 2
x = [s1,s2]; % Two-channel signal
dev = 50; % Frequency deviation in modulated signal
y = fmmod(x,Fc,Fs,dev); % Modulate both channels.
z = fmdemod(y,Fc,Fs,dev); % Demodulate both channels.
If you find thr answers useful you can both up-vote them and accept them, thanks.