# Create A Program to Create Computational Methods in Matlab Assignment Solution.

## Instructions

Objective
Write a program to create computational methods in matlab language.

## Requirements and Specifications

Source Code

CENTRED FINITE DIFFERENCE

function [t,u] = CentredFiniteDifference(Nx, tend, v0, v, u0)     % Solve     nsteps = 4*Nx;     dt = tend/double(nsteps);     dx = (2*pi)/Nx;     u = zeros(length(u0),nsteps+1);     u(:,1) = u0;     for i=1:nsteps         u(:,i+1) = u(:,i) + dt*centred_f(u(:,i), v0, v, dx);     end     t = 0:dt:tend; end PSEUDO SPECTRAL function [t,u] = PseudoSpectral(Nx, tend, v0, v, u0)     % Solve     nsteps = 4*Nx;     dt = tend/double(nsteps);     u = zeros(length(u0),nsteps+1);     u(:,1) = u0;     for i=1:nsteps         u(:,i+1) = u(:,i) + dt*spectral_f(u(:,i), v0, v);     end     t = 0:dt:tend; end 

clc, clear all, close all global v v0 %% Task 1, Part 2 v = 0.1; Nx = 64; v0 = 0.5; x = linspace(0, 2*pi, Nx); t = linspace(0, 2, 4*Nx); %% First, solve with u(0) = cos(3x) u0 = cos(3*x); [t,y1] = ode45(@(t,u)general_ivp(t,u), t, u0); %% Now, solve with u(0) = cos(7x) u0 = cos(7*x); [t,y2] = ode45(@(t,u)general_ivp(t,u), t, u0); %% Plot figure subplot(1,2,1) plot(t,y1), grid on xlabel('Time (s)'); ylabel('{u(x,t)}'); title('Solutions with u(0) = cos(3x)'); subplot(1,2,2) plot(t,y2), grid on xlabel('Time (s)'); ylabel('{u(x,t)}'); title('Solutions with u(0) = cos(7x)'); function du = spectral_ivp(t,u)     global v v0     Nx = length(u);     k = (0:Nx-1)';     du = real((1/Nx)*ifft(-v0*(1j*k).*fft(u) + v*(1j*k).^2 .*fft(u))); % du = real(-v0*ifft((1j*k)/Nx .*fft(u)) + v*ifft((1j*k).^2 /Nx .*fft(u))); end function du = general_ivp(t,u)     global v v0     Nx = length(u);     k = (0:Nx-1)';     du = (1j*k).*u.*(-v0+v*(1j*k)); end 
clc, clear all, close all %% part 1) v = 0.1; Nx = 64; v0 = 0.5; tend = 2; x = linspace(0, 2*pi, Nx); %% First, solve with u(0) = cos(3x) u0 = cos(3*x); [t,y] = PseudoSpectral(Nx, tend, v0, v, u0); %% Part 2) [t,y] = CentredFiniteDifference(Nx, tend, v0, v, u0); plot(t,y) %% Part 3 Nx = 64; Nt = 4*Nx; tend = 2; x = linspace(0, 2*pi, Nx); t = linspace(0, tend, Nt); % Create initial condition % u0 = cos(3*x); u0 = exp(-(x-pi).^2 /0.5^2); % First with v = 1.0 v = 1.0; [t11,y11] = PseudoSpectral(Nx, tend, v0, v, u0); [t12,y12] = CentredFiniteDifference(Nx, tend, v0, v, u0); % Now with v = 0.005; v = 0.005; [t21,y21] = PseudoSpectral(Nx, tend, v0, v, u0); [t22,y22] = CentredFiniteDifference(Nx, tend, v0, v, u0); % Now using Explicit Euler % Now plot figure subplot(2,2,1) plot(t11, y11) xlabel('Time (s)') title('Pseudo-Spectral Method, v = 1.0'); grid on subplot(2,2,2) plot(t21, y21) xlabel('Time (s)') title('Pseudo-Spectral Method, v = 0.005'); grid on subplot(2,2,3) plot(t12, y12) xlabel('Time (s)') title('Finite Difference Method, v = 1.0'); grid on subplot(2,2,4) plot(t22, y22) xlabel('Time (s)') title('Finite Difference Method, v = 0.005'); grid on