MATLAB - FM Modulation - matlab

I am trying to Frequency modulate a sine signal using Matlab. I have written the following code for the same:
fc = 5000; %Carrier Frequency
fs = 1000; %Signal Frequency
t = 0:0.00001:0.002;
x = sin(2*pi*fs*t);
dev = 50;
subplot(2,1,1);
plot(t,x);
y = fmmod(x,fc,fs,dev);
subplot(2,1,2);
plot(t,y);
It is able to display the first plot command but not the second one. It throws an error: `fmmod' undefined near line 10 column 5. What is wrong in the above code?

The following function will generate a FM modulated signal - it's not as good (flexible, etc) as fmmod but if you don't have the Comm System Toolbox this may be a good alternative.
function [s t] = makeFM( x, Fc, Fs, strength )
% for a signal x that modulates a carrier at frequency Fc
% produce the FM modulated signal
% works for 1 D input only
% no error checking
x = x(:);
% sampling points in time:
t = ( 0 : numel( x ) - 1 )' / Fs;
% integrate input signal
integratedX = cumsum( x ) / Fs;
s = cos( 2 * pi * ( Fc * t + strength * integratedX ));
Put this in your path and call it with similar arguments to the fmmod function (but without optional parameters):
fc = 5000; %Carrier Frequency
fs = 1000; %Signal Frequency
t = 0:0.00001:0.002;
x = sin( 2*pi*fs*t );
dev = 50;
subplot(2,1,1);
plot(t,x);
y = makeFM(x, fc, 2.5*fc, dev); % note sampling frequency must be > carrier frequency!
subplot(2,1,2);
plot(t,y);
Let me know how that works for you.

I guess this is more simple approach
clc;
clear all;
close all;
fm=input('Message Frequency=');
fc=input('Carrier Frequency=');
mi=input('Modulation Index=');
t=0:0.0001:0.1;
m=sin(2*pi*fm*t);
subplot(3,1,1);
plot(t,m);
xlabel('Time');
ylabel('Amplitude');
title('Message Signal');
grid on;
c=sin(2*pi*fc*t);
subplot(3,1,2);
plot(t,c);
xlabel('Time');
ylabel('Amplitude');
title('Carrier Signal');
grid on;
y=sin(2*pi*fc*t+(mi.*sin(2*pi*fm*t)));%Frequency changing w.r.t Message
subplot(3,1,3);
plot(t,y);
xlabel('Time');
ylabel('Amplitude');
title('FM Signal');
grid on;

Related

Optical frequency comb time to frequency domain - MATLAB

I am trying to generate ultrashort pulses and then seeing the resulting frequency comb using a fourier transform, I have used the gaussian pulse and pulse train functions to try and do this but it is not coming out correctly - I am hoping to be able to change the variables at the top to see the changes quickly
If here is a solution or any good resources that could help me I would appreciate it alot... Thanks
Code is here:
fs = 1e17 ; % sample rate
frep = 7.5e9; % repition rate
f_sig = 1.93e15; %frequency of signal
tc = gauspuls('cutoff',f_sig,100,[],-80);
t = -tc*200:1/fs:tc*200;
[x1,x2,x3] = gauspuls(t,f_sig,0.5);
figure(1);
plot(t,x1,t,x3)
xlabel('Time (s)')
ylabel('Waveform')
ts = 0:1/fs/2:tc*50000000 ;
d = 0:1/frep:tc*50000000 ; %delay
y = pulstran(ts,d,x,fs);
figure(2);
plot(ts,y)
%Frequency Comb FFT
fsamp = fs;
L= length(t); %signal length
NFFT = 2^nextpow2(L);
FFT = abs(fftshift(fft(x3,NFFT))/NFFT); %FFT with FFTshift for both negative & positive frequencies
f = fsamp*(-NFFT/2:(NFFT/2-1))/NFFT; %Frequency Vector
figure(3)
plot(f/1e9,10*log10(FFT/1e-3));
title('Magnitude of FFT');
xlabel('Frequency (GHz)');
ylabel('Magnitude |X(f)|');
%xlim([-100 100])

Plotting respiration signal in frequency domain on y axis while time is on x axis

I have a respiration (breathing) signal and a sampling frequency of 25 Hz and need to detect where is the lowest breathing frequency on a time scale, which should tell me actually when the person became sleepy. Fourier transforms in its classical form doesn't give me much useful information. So, to clarify: the time of measurement should be on the x-axis and the breathing frequency should be on the y-axis. Then, I suppose, lower amplitudes of the signal will show the slower breathing. What should be done with the signal to plot it the way I need?
All credits for this code go to Star Strider.
D = load('respiratory.txt');
Fs = 25; % Sampling Frequency (Hz)
Fn = Fs/2; % Nyquist Frequency
Ts = 1/Fs; % Sampling Time (sec)
L = numel(D);
t = linspace(0, L, L)*Ts; % Time Vector (sec)
figure(1)
plot(t, D)
grid
% axis([0 60 -850 -750])
axis([xlim -850 -750])
xlabel('Time')
ylabel('Amplitude')
FTD = fft(D-mean(D))/L; % Fourier Transform
Fv = linspace(0, 1, fix(L/2)+1)*Fn; % Frequency Vector
Iv = 1:numel(Fv); % Index Vector
figure(2)
plot(Fv, abs(FTD(Iv))*2)
grid
axis([0 2.5 ylim])
xlabel('Frequency (Hz)')
ylabel('Amplitude')
Wp = [0.35 0.65]/Fn; % Passband Frequency (Normalised)
Ws = [0.30 0.75]/Fn; % Stopband Frequency (Normalised)
Rp = 1; % Passband Ripple (dB)
Rs = 50; % Stopband Ripple (dB)
[n,Ws] = cheb2ord(Wp,Ws,Rp,Rs); % Filter Order
[z,p,k] = cheby2(n,Rs,Ws); % Filter Design, Sepcify Bandpass
[sos,g] = zp2sos(z,p,k); % Convert To Second-Order-Section For Stability
figure(3)
freqz(sos, 2^16, Fs) % Filter Bode Plot
D_filtered = filtfilt(sos, g, D); % Filter Signal
[pks,locs] = findpeaks(D_filtered, 'MinPeakDist',40);
figure(4)
plot(t, D_filtered)
hold on
plot(t(locs), pks, '^r')
hold off
grid
% axis([0 60 ylim])
axis([0 60 -15 15])
xlabel('Time')
ylabel('Amplitude')
tdif = diff([0 t(locs)]); % Time Difference Between Peaks (sec)
Dfrq = 60./tdif; % Frequency (Respirations/Minute)
figure(5)
plot(t(locs), Dfrq)
grid
axis([xlim 10 40])
xlabel('Time (sec)')
ylabel('Frequency (minute^{-1})')

Bandpass filter failing to filter unwanted frequencies in matlab

I'm making a bandpass filter and I've created a signal with some unwanted frequencies based on sinusoids:
Fs = 8e3; % Sampling Rate
fn = Fs/2; % Nyquist frequency
L = 1e3; % Length of signal
T = 1/Fs; % Sampling period
t = T*linspace(0,L,Fs); % Time domain
% Frequencies in Hz
f1 = 1500;
f2 = 700;
f3 = 2500;
f4 = 3500;
% Signal
x = 6*sin(2*pi*f1*t);
% Noise
noise = 3*sin(2*pi*f2*t)...
+ 2*sin(2*pi*f3*t)...
+ 1*sin(2*pi*f4*t);
x_noise = x + noise;
I then create a Butterworth bandpass filter:
[b,a] = butter(10,[1000 2000]/fn,'bandpass');
The signal in time and frequency space, with the bandpass response (with freqz) looks like this:
Fig. 1 Signal with corruption | Fig. 2 Frequency with bandpass response
I would've figured from here on, simply doing
xf = filter(b,a,x_noise);
would've yielded something very similar to the original signal, but alas, what I get is really far from the filtered signal with a high response far from the bandpass.
What am I doing wrong here?
Here's the full code:
clear all
Fs = 8e3; % Sampling Rate
fn = Fs/2; % Nyquist frequency
L = 1e3; % Length of signal
T = 1/Fs; % Sampling period
t = T*linspace(0,L,Fs); % Time domain
% Frequencies in Hz
f1 = 1500;
f2 = 700;
f3 = 2500;
f4 = 3500;
% Signal
x = 6*sin(2*pi*f1*t);
% Noise
noise = 3*sin(2*pi*f2*t)...
+ 2*sin(2*pi*f3*t)...
+ 1*sin(2*pi*f4*t);
x_noise = x + noise;
subplot(221);
idx = 1:round(length(t)/30);
plot(t(idx),x(idx),t(idx),x_noise(idx));
xlabel('Time (s)'); ylabel('Signal Amplitudes');
legend('Original signal','Noisy signal');
% Frequency space
f = fn*linspace(0,1,L/2+1);
X = fft(x_noise)/L;
[b,a] = butter(10,[1000 2000]/fn,'bandpass');
h = abs(freqz(b,a,floor(L/2+1)));
subplot(222);
plot(f,abs(X(1:L/2+1)),f,h*max(abs(X)));
xlabel('Freq (Hz)'); ylabel('Frequency amplitudes');
legend('Fourier Transform of signal','Filter amplitude response');
% Filtered signal
xf = filter(b,a,x_noise);
subplot(223)
plot(t(idx),xf(idx));
xlabel('Time (s)'); ylabel('Signal Amplitudes');
legend('Filtered signal');
% Filtered in frequency space
Xf = abs(fft(xf)/L);
subplot(224);
plot(f,Xf(1:L/2+1),f,h*5e-6);
xlabel('Freq (Hz)'); ylabel('Frequency amplitudes');
legend('Fourier Transform of filtered signal','Bandpass');
Your time variable t is wrong, e.g 1/(t(2)-t(1)) should give Fs but it doesn't.
Try instead:
t = T*(0:L-1);

I want the convolution plot of f1 and f2 in the below program

In this code f1 and f2 are the Fourier Transform of Gate and Train of Impulse..
I need the plot of convolution between these two spectrums
I am expecting train of sinc function since convolution of a signal with train of impulse gives train of that func..
but using direct conv() I am getting a positive sine pulse...
fSampling = 10000; %Sampling Frequency
tSampling = 1/fSampling; %Sampling Time
L = 10000; %Length of Signal
to = (0:L-1)*tSampling; %Time Vector
F = 100;
% message signal
t = -5:0.01:5;
w=1;
a= rectpuls(t,2);
subplot(2,4,1);
plot(t,a);
xlabel('Time');
ylabel('Amplitude');
title('Message signal');
grid on;
% Fourier transform of sine wave
subplot(2,4,2)
NFFT = 2^nextpow2(L);
Xsig = fft(a,NFFT)/L;
f1 = fSampling/2*(linspace(0,1,NFFT/2+1));
plot(f1,2*abs(Xsig(1:NFFT/2+1)),'r');
grid on;
axis([-50 500 1.0000e-005 1])
title('\itSignle-Sided Amplitude Sepectrum of xsig(t)');
xlabel('\itFrequency(Hz) \rightarrow');
ylabel('|Xsig(f)| \rightarrow');
% train of impulse
n= -5:1:5;
l =length(n);
for i= 1:l
x(i)=1;
end;
subplot(2,4,3);
stem(n,x);
xlabel('Time');
ylabel('Amplitude');
title('Train of Impulses');
grid on;
% Fourier Transform of Train of Impulse
subplot(2,4,4)
NFFT = 2^nextpow2(L);
Xsig = fft(x,NFFT)/L;
f2 = fSampling/2*(linspace(0,1,NFFT/2+1));
stem(f2,2*abs(Xsig(1:NFFT/2+1)),'r');
grid on;
axis([-50 500 1.0000e-005 1])
title('\itSignle-Sided Amplitude Sepectrum of xsig(t)');
xlabel('\itFrequency(Hz) \rightarrow');
ylabel('|Xsig(f)| \rightarrow');
% multiplication of signals
T = -5:0.01:5;
b = a.*x(i);
subplot(2,4,5);
stem(T,b);
xlabel('Time');
ylabel('Amplitude');
title('Sampled signal');
grid on;
% Fourier transform of Sampled Signal
subplot(2,4,6)
NFFT = 2^nextpow2(L);
Xsig = fft(x,NFFT)/L;
f3 = fSampling/2*(linspace(0,1,NFFT/2+1));
plot(f3,2*abs(Xsig(1:NFFT/2+1)),'r');
grid on;
axis([-50 500 1.0000e-005 1])
title('\itSignle-Sided Amplitude Sepectrum of xsig(t)');
xlabel('\itFrequency(Hz) \rightarrow');
ylabel('|Xsig(f)| \rightarrow');
%Convolution of
c= conv(f1,f2)
subplot(2,4,7);
plot(c);
grid on;

Fourier transform and LTI filter and frequency response in Matlab

I'm new to Matlab for LTI signal processing and wondering if anyone can help with something that I'm sure is meant to be basic. I've spent hours and hours researching and obtaining background information and still cannot obtain a clear path to tackle these problems. So far, from scratch, I have generated a signal required and managed to use the fft function to produce the signal's DFT:
function x = fourier_rikki(A,t,O)
Fs = 1000;
t = 0:(1/Fs):1;
A = [0.5,0,0.5];
N = (length(A) - 1)/2;
x = zeros(size(t));
f1 = 85;
O1 = 2*pi*f1;
for k = 1:length(A)
x1 = x + A(k)*exp(1i*O1*t*(k-N-1));
end
f2 = 150;
O2 = 2*pi*f2;
for k = 1:length(A);
x2 = x + A(k)*exp(1i*O2*t*(k-N-1));
end
f3 = 330;
O3 = 2*pi*f3;
for k = 1:length(A);
x3 = x + A(k)*exp(1i*O3*t*(k-N-1));
end
signal = x1 + x2 + x3;
figure(1);
subplot(3,1,1);
plot(t, signal);
title('Signal x(t) in the Time Domain');
xlabel('Time (Seconds)');
ylabel('x(t)');
X = fft(signal); %DFT of the signal
subplot(3,1,2);
plot(t, X);
title('Power Spectrum of Discrete Fourier Transform of x(t)');
xlabel('Time (Seconds)');
ylabel('Power');
f = linspace(0, 1000, length(X)); %?
subplot(3,1,3);
plot(f, abs(X)); %Only want the positive values
title('Spectral Frequency');
xlabel('Frequency (Hz)'); ylabel('Power');
end
At this stage, I'm assuming this is correct for:
"Generate a signal with frequencies 85,150,330Hz using a sampling frequency of 1000Hz - plot 1seconds worth of the signal and its Discrete Fourier Transform."
The next step is to "Find the frequency response of an LTI system that filters out the higher and lower frequencies using the Fourier Transform". I'm stuck trying to create an LTI system that does that! I have to be left with the 150Hz signal, and I'm guessing I perform the filtering on the FFT, perhaps using conv.
My course is not a programming course - we are not assessed on our programming skills and I have minimal Matlab experience - basically we have been left to our own devices to struggle through, so any help would be greatly appreciated! I am sifting through tonnes of different examples and searching Matlab functions using 'help' etc, but since each one is different and does not have a break down of the variables used, explaining why certain parameters/values are chosen etc. it is just adding to the confusion.
Among many (many) others I have looked at:
http://www.ee.columbia.edu/~ronw/adst-spring2010/lectures/matlab/lecture1.html
http://gribblelab.org/scicomp/09_Signals_and_sampling.html section 10.4 especially.
As well as Matlab Geeks examples and Mathworks Matlab function explanations.
I guess the worst that can happen is that nobody answers and I continue burning my eyeballs out until I manage to come up with something :) Thanks in advance.
I found this bandpass filter code as a Mathworks example, which is exactly what needs to be applied to my fft signal, but I don't understand the attenuation values Ast or the amount of ripple Ap.
n = 0:159;
x = cos(pi/8*n)+cos(pi/2*n)+sin(3*pi/4*n);
d = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',1/4,3/8,5/8,6/8,60,1,60);
Hd = design(d,'equiripple');
y = filter(Hd,x);
freq = 0:(2*pi)/length(x):pi;
xdft = fft(x);
ydft = fft(y);
plot(freq,abs(xdft(1:length(x)/2+1)));
hold on;
plot(freq,abs(ydft(1:length(x)/2+1)),'r','linewidth',2);
legend('Original Signal','Bandpass Signal');
Here is something you can use as a reference. I think I got the gist of what you were trying to do. Let me know if you have any questions.
clear all
close all
Fs = 1000;
t = 0:(1/Fs):1;
N = length(t);
% 85, 150, and 330 Hz converted to radian frequency
w1 = 2*pi*85;
w2 = 2*pi*150;
w3 = 2*pi*330;
% amplitudes
a1 = 1;
a2 = 1.5;
a3 = .75;
% construct time-domain signals
x1 = a1*cos(w1*t);
x2 = a2*cos(w2*t);
x3 = a3*cos(w3*t);
% superposition of 85, 150, and 330 Hz component signals
x = x1 + x2 + x3;
figure
plot(t(1:100), x(1:100));
title('unfiltered time-domain signal, amplitude vs. time');
ylabel('amplitude');
xlabel('time (seconds)');
% compute discrete Fourier transform of time-domain signal
X = fft(x);
Xmag = 20*log10(abs(X)); % magnitude spectrum
Xphase = 180*unwrap(angle(X))./pi; % phase spectrum (degrees)
w = 2*pi*(0:N-1)./N; % normalized radian frequency
f = w./(2*pi)*Fs; % radian frequency to Hz
k = 1:N; % bin indices
% plot magnitude spectrum
figure
plot(f, Xmag)
title('frequency-domain signal, magnitude vs. frequency');
xlabel('frequency (Hz)');
ylabel('magnitude (dB)');
% frequency vector of the filter. attenuates undesired frequency components
% and keeps desired components.
H = 1e-3*ones(1, length(k));
H(97:223) = 1;
H((end-223):(end-97)) = 1;
% plot magnitude spectrum of signal and filter
figure
plot(k, Xmag)
hold on
plot(k, 20*log10(H), 'r')
title('frequency-domain signal (blue) and filter (red), magnitude vs. bin index');
xlabel('bin index');
ylabel('magnitude (dB)');
% filtering in frequency domain is just multiplication
Y = X.*H;
% plot magnitude spectrum of filtered signal
figure
plot(f, 20*log10(abs(Y)))
title('filtered frequency-domain signal, magnitude vs. frequency');
xlabel('frequency (Hz)');
ylabel('magnitude (dB)');
% use inverse discrete Fourier transform to obtain the filtered time-domain
% signal. This signal is complex due to imperfect symmetry in the
% frequency-domain, however the imaginary components are nearly zero.
y = ifft(Y);
% plot overlay of filtered signal and desired signal
figure
plot(t(1:100), x(1:100), 'r')
hold on
plot(t(1:100), x2(1:100), 'linewidth', 2)
plot(t(1:100), real(y(1:100)), 'g')
title('input signal (red), desired signal (blue), signal extracted via filtering (green)');
ylabel('amplitude');
xlabel('time (seconds)');
Here is the end result...