Triangle Pulse with fourier transformation - matlab

I have a basic exercise for telecommunications with matlab, and i must plot a triangle pulse with (-c,0) to (c,0) with c = 6 and Amplitude = 1 in a for loop for M pulses and approach the periodic pulse using N Fourier series terms. I can't find something on the internet that can help me so far.
A similar code for rect pulse that I made and works is this:
a = 1;
b = 3;
N = 1000;
t = linspace(a-2*a,b+2*b,N);
A = 1;
y = rect_pulse(A,a,b,t);
plot(t,y);
grid on
axis([a-2*a b+2*b 0 2*A]);
M = 5;
T=7;
t_new = linspace(a-2*a,b+(M-1)*T+2*b,N);
y_new = zeros(1,N);
for index = 1:1:M
temp_y = rect_pulse(A,a+(index-1)*T,b+(index-1)*T,t_new);
y_new = y_new + temp_y;
end
figure;
plot(t_new,y_new);
grid on;
axis([a-2*a b+(M-1)*T+2*b 0 2*A]);
Where rect_pulse is this:
function y = rect_pulse (A,a,b,t)
N=length(t);
y = zeros(1,N);
for index = 1:1:N
if(t(1,index)>=a) && (t(1,index)<=b)
y(1,index) = A;
end
end
And fourier series is this:
function y_fourier = fourier_series_rect_pulse(a,b,To,N,t)
y_fourier = 0;
wo = (2*pi)/To;
for n = -N:1:N
f_real = #(x) cos(n*wo*x);
f_imag = #(x) sin(n*wo*x);
cn = (1/To)*(quad(f_real,a,b)) - j*quad(f_imag,a,b));
y_fourier = y_fourier + cn*exp(j*n*wo*t);
end
y_fourier = real(y_fourier);
Any ideas how to make this in to triangle pulse?

This probably deviates significantly from your approach but if you're curious here is a script I came up with to generate a triangular pulse train that can be adjusted. This method, unfortunately, uses the fft() function which may or may not be off-limits in your case. Most of the script uses indexing and manipulating vectors. Additional spectral components may be seen due to the DC offset of the alternating triangular wave and the limited number of cycles available in the vector representation of the triangular wave.
Triangular Pulses and Fourier Transforms:
Triangular Pulse with Duty-Off Period:
Higher frequency spectral components present due to the abrupt corners that occur at the transition states of the triangle pulse and duty-off period.
%******************************************************%
%PROPERTIES THAT CAN BE CHANGED%
%******************************************************%
Plotting_Interval = 0.01; %0.01 seconds%
Pulse_Width = 1/20; %6 seconds%
Period = 1/20; %10 seconds (should be at least the pulse width)%
Start_Time = 0;
End_Time = Pulse_Width*1000; %(1000 pulses)%
%******************************************************%
if(Period < Pulse_Width)
Period = Pulse_Width;
end
Time_Vector = (Start_Time: Plotting_Interval: End_Time);
Points_Per_Unit_Time = 1/Plotting_Interval;
Half_Pulse = Pulse_Width/2;
Number_Of_Points = Pulse_Width/Plotting_Interval;
Rising_Slope = linspace(0,1,floor(Number_Of_Points/2) + 1);
Falling_Slope = 1 - Rising_Slope;
Triangular_Pulse = [Rising_Slope Falling_Slope(2:end)];
t = (0: Plotting_Interval: Pulse_Width);
Periodic_Triangular_Pulse = zeros(1,length(Time_Vector));
for Cycle = 1: +Period/Plotting_Interval: End_Time/Plotting_Interval
Periodic_Triangular_Pulse(1,Cycle:Cycle+length(Triangular_Pulse)-1) = Triangular_Pulse(1,1:end);
end
Periodic_Triangular_Pulse = Periodic_Triangular_Pulse(1,1:length(Time_Vector));
subplot(1,2,1); plot(Time_Vector,Periodic_Triangular_Pulse);
Triangle_Frequency = 1/Period;
title("Triangular Pulse Train " + num2str(Triangle_Frequency) + "Hz (first 10 cycles)");
axis([0 Period*10 0 1]);
xlabel("Time (s)"); ylabel("Amplitude");
Signal_Length = length(Periodic_Triangular_Pulse);
Fourier_Transform = fft(Periodic_Triangular_Pulse);
Fs = 1/Plotting_Interval;
P2 = abs(Fourier_Transform/Signal_Length);
P1 = P2(1:floor(Signal_Length/2)+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(Signal_Length/2))/Signal_Length;
subplot(1,2,2); plot(f,P1)
title("Single-Sided Fourier Transform");
xlabel("Frequency (Hz)"); ylabel("Magnitude");
Ran using MATLAB R2019b

Related

How do I fix my code to find the convergence rate

The IBVP is
u_t+2u_x=0 , 0<x<1, t>0
u(x,0)=sin(pi*x)
u(0,t)=g(t)=sin(-2*pi*t)
I have to first implement the scheme using 4th-order central difference SBP operator in space and RK4 in time with spacing xi=i*h, i=0,1,...,N and update g(t) at every RK stage. Also, using the code compute the convergence rate on a sequence of grids.
Below I have shown my working which is not helping me find the convergence rate so can anyone help me with finding my mistakes.
%Parameters
nstp = 16; %number of grid points in space
t0 = 0; %initial time
tend = 1; %end time
x0 = 0; %left boundary
xN = 1; %right boundary
x = linspace(0,1,nstp); %points in space
h = xN-x0/nstp-1; %grid size
cfl = 4;
k = cfl*h; %length of time steps
N = ceil(tend/k); %number of steps in time
k = tend/N; %length of time steps
u0 = sin(pi*x); %initial data
e = zeros(nstp);
e(1) = 1;
e0 = e(:,1);
m = zeros(nstp);
m(1) = sin(-2*pi*tend);
g = m(:,1);
%4th order central SBP operator in space
m=10; %points
H=diag(ones(m,1),0);
H(1:4,1:4)=diag([17/48 59/48 43/48 49/48]);
H(m-3:m,m-3:m)=fliplr(flipud(diag([17/48 59/48 43/48 49/48])));
H=H*h;
HI=inv(H);
D1=(-1/12*diag(ones(m-2,1),2)+8/12*diag(ones(m-1,1),1)- ...
8/12*diag(ones(m-1,1),-1)+1/12*diag(ones(m-2,1),-2));
D1(1:4,1:6)=[-24/17,59/34,-4/17,-3/34,0,0; -1/2,0,1/2,0,0,0;
4/43,-59/86,0,59/86,-4/43,0; 3/98,0,-59/98,0,32/49,-4/49];
D1(m-3:m,m-5:m)=flipud( fliplr(-D1(1:4,1:6)));
D1=D1/h;
%SBP-SAT scheme
u = -2*D1*x(1:N-1)'-(2*HI*(u0-g)*e);
%Runge Kutta for ODE
for i=1:nstp %calculation loop
t=(i-1)*k;
k1=D*u;
k2=D*(u+k*k1/2);
k3=D*(u+k*k2/2);
k4=D*(u+k*k3);
u=u+(h*(k1+k2+k3+k4))/6; %main equation
figure(1)
plot(x(1:N-1),u); %plot
drawnow
end
%error calculcation
ucorrect = sin(pi*(x-2*tend)); %correct solution
ucomp = u(:,end); %computed solution
errornorm = sqrt((ucomp-ucorrect)'*H*(ucomp-ucorrect)); %norm of error**
One egregious error is
h = xN-x0/nstp-1; %grid size
You need parentheses here, else you compute h as xN-(x0/nstp)-1=1-(0/nstp)-1=0.
Or avoid this all and use the actual grid step. Also, if nstp is the number of steps or segments in the subdivision, the number of nodes is one larger. And if you define x0,xN then you should also actually use them.
x = linspace(x0,xN,nstp+1); %points in space
h = x(2)-x(1); %grid size
As to the SBP-SAT approach, the space discretization gives
u_t(t) + 2*D_1*u(t) = - H_inv * (dot(e_0,u(t)) - g(t))*e_0
which should give the MoL ODE function as
F = #(u,t) -2*D1*u - HI*e0*(u(1)-g(t))
The matrix construction has to be adapted to have the correct extends for these changed operations.
The implement RK4 as
k1 = F(u,t)
k2 = F(u+0.5*h*k1, t+0.5*h)
...
In total this gives a modified script below. Stable solutions only occur for cfl=1 or below. With that the errors seemingly behave like 4th order. The factor for the initial condition also works best in the range 0.5 to 1, larger factors tend to increase the error at x=0, at least in the initial time steps. With the smaller factors the error is uniform over the interval.
%Parameters
xstp = 16; %number of grid points in space
x0 = 0; %left boundary
xM = 1; %right boundary
x = linspace(x0,xM,xstp+1)'; %points in space
h = x(2)-x(1); %grid size
cfl = 1;
t0 = 0; %initial time
tend = 1; %end time
k = cfl*h; %length of time steps
N = ceil(tend/k); %number of steps in time
k = tend/N; %length of time steps
u = sin(pi*x); %initial data
e0 = zeros(xstp+1,1);
e0(1) = 1;
g = #(t) sin(-2*pi*t);
%4th order central SBP operator in space
M=xstp+1; %points
H=diag(ones(M,1),0); % or eye(M)
H(1:4,1:4)=diag([17/48 59/48 43/48 49/48]);
H(M-3:M,M-3:M)=fliplr(flipud(diag([17/48 59/48 43/48 49/48])));
H=H*h;
HI=inv(H);
D1=(-1/12*diag(ones(M-2,1),2)+8/12*diag(ones(M-1,1),1)- ...
8/12*diag(ones(M-1,1),-1)+1/12*diag(ones(M-2,1),-2));
D1(1:4,1:6) = [ -24/17, 59/34, -4/17, -3/34, 0, 0;
-1/2, 0, 1/2, 0, 0, 0;
4/43, -59/86, 0, 59/86, -4/43, 0;
3/98, 0, -59/98, 0, 32/49, -4/49 ];
D1(M-3:M,M-5:M) = flipud( fliplr(-D1(1:4,1:6)));
D1=D1/h;
%SBP-SAT scheme
F = #(u,t) -2*D1*u - 0.5*HI*(u(1)-g(t))*e0;
clf;
%Runge Kutta for ODE
for i=1:N %calculation loop
t=(i-1)*k;
k1=F(u,t);
k2=F(u+0.5*k*k1, t+0.5*k);
k3=F(u+0.5*k*k2, t+0.5*k);
k4=F(u+k*k3, t+k);
u=u+(k/6)*(k1+2*k2+2*k3+k4); %main equation
figure(1)
subplot(211);
plot(x,u,x,sin(pi*(x-2*(t+k)))); %plot
ylim([-1.1,1.1]);
grid on;
legend(["computed";"exact"])
drawnow
subplot(212);
plot(x,u-sin(pi*(x-2*(t+k)))); %plot
grid on;
hold on;
drawnow
end
%error calculcation
ucorrect = sin(pi*(x-2*tend)); %correct solution
ucomp = u; %computed solution
errornorm = sqrt((ucomp-ucorrect)'*H*(ucomp-ucorrect)); %norm of error**

FastICA Implementation.. Matlab

I have been working on a FastICA algorithm implementation using MatLab. Currently the code does not separate the signals as good as id like. I was wondering if anyone here could give me some advice on what I could do to fix this problem?
disp('*****Importing Signals*****');
s = [1,30000];
[m1,Fs1] = audioread('OSR_us_000_0034_8k.wav', s);
[f1,Fs2] = audioread('OSR_us_000_0017_8k.wav', s);
ss = size(f1,1);
n = 2;
disp('*****Mixing Signals*****');
A = randn(n,n); %developing mixing matrix
x = A*[m1';f1']; %A*x
m_x = sum(x, n)/ss; %mean of x
xx = x - repmat(m_x, 1, ss); %centering the matrix
c = cov(x');
sq = inv(sqrtm(c)); %whitening the data
x = c*xx;
D = diff(tanh(x)); %setting up newtons method
SD = diff(D);
disp('*****Generating Weighted Matrix*****');
w = randn(n,1); %Random weight vector
w = w/norm(w,2); %unit vector
w0 = randn(n,1);
w0 = w0/norm(w0,2); %unit vector
disp('*****Unmixing Signals*****');
while abs(abs(w0'*w)-1) > size(w,1)
w0 = w;
w = x*D(w'*x) - sum(SD'*(w'*x))*w; %perform ICA
w = w/norm(w, 2);
end
disp('*****Output After ICA*****');
sound(w'*x); % Supposed to be one of the original signals
subplot(4,1,1);plot(m1); title('Original Male Voice');
subplot(4,1,2);plot(f1); title('Original Female Voice');
subplot(4,1,4);plot(w'*x); title('Post ICA: Estimated Signal');
%figure;
%plot(z); title('Random Mixed Signal');
%figure;
%plot(100*(w'*x)); title('Post ICA: Estimated Signal');
Your covariance matrix c is 2 by 2, you cannot work with that. You have to mix your signal multiple times with random numbers to get anywhere, because you must have some signal (m1) common to different channels. I was unable to follow through your code for fast-ICA but here is a PCA example:
url = {'https://www.voiptroubleshooter.com/open_speech/american/OSR_us_000_0034_8k.wav';...
'https://www.voiptroubleshooter.com/open_speech/american/OSR_us_000_0017_8k.wav'};
%fs = 8000;
m1 = webread(url{1});
m1 = m1(1:30000);
f1 = webread(url{2});
f1 = f1(1:30000);
ss = size(f1,1);
n = 2;
disp('*****Mixing Signals*****');
A = randn(50,n); %developing mixing matrix
x = A*[m1';f1']; %A*x
[www,comp] = pca(x');
sound(comp(:,1)',8000)

Solving Coupled partial differential equations of stiff nature using MATLAB

I want to solve coupled partial differential equations of first order, which are of stiff nature. I have coded in MATLAB to solve this pde's, I have used Method of line to convert PDE into ODE, and i have used beam and warmings(second order upwind) method to discritize the spatial derivative. The discretization method is total variation diminishing(TVD) to eliminate the oscillation. But rather using TVD and ode15s solver to integrate resultant stiff ode's the resultant plot is oscillatory(not smooth). What should i do to eliminate this oscillation and get correct results.
I have attached my MATLAB code.. please see it and suggest some improvement.
∂y(1)/∂t=-0.1 ∂y(1)/∂x + (0.5*e^(15*(y(2)⁄(1+y(2))))*(1- y(1))
∂y(2)/∂t=-0.1 ∂y(2)/∂x - (0.4*e^(15*(y(2)⁄(1+y(2))))*(1- y(1))-0.4
Initial condition: at t = 0 y(1)= y(2)=0
Boundary condition: y(1)= y(2) = 0 at x=0
I have attached my MATLAB code.. please see it and suggest some improvement.
function brussode(N)
if nargin<1
N = 149;
end
tspan = [0 10];
m = 0.00035
t = (1:N)/(N+1)*m;
y0 = [repmat(0,1,N); repmat(0,1,N)];
p = 0.5
q = 0.4
options = odeset('Vectorized','on','JPattern',jpattern(N));
[t,y] = ode15s(#f,tspan,y0,options);
a = size(y,2)
u = y(:,1:2:end);
x = (1:N)/(N+1);
figure;
%surf(x,t(end,:),u);
plot(x,u(end,:))
xlabel('space');
ylabel('solution');
zlabel('solution u');
%--------------------------------------------------------------
%Nested function -- N is provided by the outer function.
%
function dydt = f(t,y)
%Derivative function
dydt = zeros(2*N,size(y,2)); %preallocate dy/dt
x = (1:N)/(N+1);
% Evaluate the 2 components of the function at one edge of the grid
% (with edge conditions).
i = 1;
%y(1,:) = 0;
%y(2,:) = 0;
dydt(i,:) = -0.1*(N+1)*(y(i+2,:)-0)+ (0.01/2)*m*((N+1).^3)*(y(i+2,:)-0) + p*exp(15*(0/(1+0)))*(1-0);
dydt(i+1,:) = -0.1*(N+1)*(y(i+3,:)-0)+ (0.01/2)*m*((N+1).^3)*(y(i+3,:)-0) - q*exp(15*(0/(1+0)))*(1-0)+0.25;
i = 3;
%y(1,:) = 0;
%y(2,:) = 0;
dydt(i,:) = -0.1*(N+1)*(y(i+2,:)-y(i,:)) + (0.01/2)*m*((N+1).^3)*(y(i+3,:)-y(i,:)) + p*exp(15*(y(i+1,:)/(1+y(i+1,:))))*(1-y(i,:));
dydt(i+1,:) = -0.1*(N+1)*(y(i+3,:)-y(i+1,:)) + (0.01/2)*m*((N+1).^3)*(y(i+3,:)-y(i,:)) - q*exp(15*(y(i+1,:)/(1+y(i+1,:))))*(1-y(i,:))+0.25;
%Evaluate the 2 components of the function at all interior grid
%points.
i = 5:2:2*N;
%y(1,:) = 0;
% y(2,:) = 0;
dydt(i,:) = (-0.1/2)*(N+1)*(3*y(i,:)-4*y(i-2,:)+y(i-4,:)) +(0.01/2)*m*((N+1).^3)*(y(i,:)-2*y(i-2,:)+y(i-4,:))+ p*exp(15*(y(i+1,:)/(1+y(i+1,:))))*(1-y(i,:));
dydt(i+1,:) = (-0.1/2)*(N+1)*(3*y(i+1,:)-4*y(i-1,:)+y(i-3,:))+(0.01/2)*m*((N+1).^3)*(y(i+1,:)-2*y(i-1,:)+y(i-3,:)) - q*exp(15*(y(i+1,:)/(1+y(i+1,:))))*(1-y(i,:))+0.25;
end
%-------------------------------------------------------------
end %brussode
%-------------------------------------------------------------
% Subfunction -- the sparsity pattern
%
function S = jpattern(N)
% Jacobian sparsity patter
B = ones(2*N,5);
B(2:2:2*N,2) = zeros(N,1);
B(1:2:2*N-1,4) = zeros(N,1);
S = spdiags(B,-2:2,2*N,2*N);
end
%-------------------------------------------------------------

Solving ring laser equations in MATLAB using ode

I have written a Matlab code which is a simulation of NOT gate implementation using ring lasers. Si variable is input in my code. But my code works only for Si = 0. for any other non zero value it doesn't show output.
%-----------Rate Equation MATLAB code ---------
function dydt = requations(t,y)
dydt = zeros(size(y));
%prompt = 'Sinput???';
%Si = input(prompt);
Si = 0; %MY INPUT
q = 1.6e-19; % charge of electron
tau_e = 1e-9; % carrier lifetime
No = 3.3e18; % # No of carriers at transparency
a = 1e-15; % Linear gain coefficient
Vg = 7.5e9; % group velocity
Vp = 3e-11; %Photon reservoir volume
V = 1e-11; %Carrier reservoir Volume
tau_p = 1.7e-12; % photon lifetime
beta = 1e-5; % spontateous emission coefficient
eps = 7.5e-17; % Nonlinear gain suppression coefficient
Ni = 0.8; %Internal quantum efficiency
w = 2*pi*10e5;
Io = 10e-3;
%I = Io*sin(w*t);
I = 2.5*Io; %for test purposes
tp = 1/tau_p;
te = 1/tau_e;
Aint = 6; %Internal losses inside cavity waveguides
%G = ((a/Vp)* (N-(V*No)))/(1-eps*(Sc + Scc));
alpha = -2; %alpha factor
L = 76e-4 ;%size of the ring
wcb = 2*pi*70;
%R = 0.25;
Wcb = wcb*1000000;
%r = 1/R;
tpcw = Vg*(Aint + ((1/L)*log(4)));
Tpcw = 1/tpcw;
%------Rate equations-------
N = y(1);
Sc = y(2); %Clock wise photon number
yc = y(3);
Scc = y(4); %anti clockwise photon number
ycc = y(5);
G = ((a/Vp)* (N-(V*No)))/(1-eps*(Sc + Scc));
dydt(1) = (Ni*I)/q - y(1)*te - Vg*G*(y(2) + y(4)); %dN/dt
dydt(2) = (Vg*G-Tpcw)*y(2) + beta*y(1)*te; %dSc/dt
dydt(3) = -(alpha/2)*(Vg*G-Tpcw); %dyc/dt
dydt(4) = (Vg*G-Tpcw)*y(4) + beta*y(1)*te + ((2*Vg)/L)*cos(y(5))*(sqrt(Si*y(4))); %dScc/dt
dydt(5) = -Wcb - ((alpha/2)*(Vg*G-Tpcw)) - ((Vg/L)*sin(y(5))*(sqrt(Si/y(4)))); %dycc/dt
Below is the Ode file
%------Rate equations for requation file------
format bank;
close all;
clear all;
clc;
%time interval
ti=0;
tf=200;
tspan=[ti tf];
x0 = [3.75e7, 2.25e6, 0, 2.25e6, 0]; %initial vectors
%options= odeset('RelTol',100, 'AbsTol',[3.75e7, 2.25e6]);
[t,y]= ode23t(#requations,tspan,x0);
%Plotting the graphs:
figure
subplot(5,1,1), plot(t,y(:,1),'r'),grid on;
title('Laserrate equations'),ylabel('N');
subplot(5,1,2), plot(t,y(:,2),'b'),grid on;
ylabel('Scw'); xlabel('t');
subplot(5,1,3), plot(t,y(:,3),'g'),grid on;
ylabel('ycw');xlabel('t');
subplot(5,1,4), plot(t,y(:,3),'g'),grid on;
ylabel('Sccw');xlabel('t');
subplot(5,1,5), plot(t,y(:,3),'g'),grid on;
ylabel('yccw');xlabel('t');

spectral structure of sinusoidal model

let us consider following code
function [ x ] = generate1(N,m,A3)
f1 = 100;
f2 = 200;
T = 1./f1;
t = (0:(N*T/m):(N*T))'; %'
wn = randn(length(t),1); %zero mean variance 1
x = 20.*sin(2.*pi.*f1.*t) + 30.*cos(2.*pi.*f2.*t) + A3.*wn;
%[pks,locs] = findpeaks(x);
%plot(x);
end
as i know peaks in Fourier domain represent at this frequency,which are present in signal,for example let us take plot of Fourier transform of this signal
let us run this signal
y=generate1(3,500,1);
and plot
plot(abs(fft(y)))
but clearly it does not shows me peaks at frequency given in signal,what is problem?please help me,generally it is stationary signal,that why this graph should show me exact picture but it does not do,why?
EDITED :
y1=generate1(3,500,0);
function [ x, fs ] = generate1(N,m,A3)
f1 = 100;
f2 = 200;
T = 1./f1;
t = (0:(N*T/m):(N*T))'; %'
wn = randn(length(t),1); %zero mean variance 1
x = 20.*sin(2.*pi.*f1.*t) + 30.*cos(2.*pi.*f2.*t) + A3.*wn;
%[pks,locs] = findpeaks(x);
%plot(x);
fs = 1/(t(2)-t(1));
end
and see
absfft = abs(fft(y));
plot(fs/2*linspace(0,1,length(absfft)/2+1),2*absfft(1:end/2+1))
or
plot(linspace(-fs/2,fs/2,length(absfft)),fftshift(absfft))
the x-axis in your plot is from 0 to fs/2 and then from -fs/2 to 0