echo off;
% NUMERICAL METHODS: MATLAB Programs, (c) John H. Mathews 1994
% To accompany the text:
% NUMERICAL METHODS for Mathematics, Science and Engineering, 2nd Ed, 1992
% Prentice Hall, Englewood Cliffs, New Jersey, 07632, U.S.A.
% This free software is complements of the author.

% Algorithm 10.1 (Finite-Difference Solution for the Wave Equation).
% Section 10.1, Hyperbolic Equations, Page 507
echo on; clc; format short; hold off; clear

% HYPERBOLIC PDE's.
% Finite difference solution for the wave equation

% 2
% u (x,t) = c u (x,t) with
% tt xx

% u(0,t) = 0 and u(a,t) = 0 for 0 ² t ² b.

% u(x,0) = f(x) and u (x,0) = g(x) for 0 < x < a.
% t

% A numerical approximation is computed over the rectangle

% 0 ² x ² a , 0 ² t ² b.

pause % Press any key to continue.

clc;
% Store f(x) and g(x) in the M-files f.m and g.m respectively.
% function z = f(x)
% z = sin(pi*x) + sin(2*pi*x);

% function z = g(x)
% z = 0;

delete f.m
diary f.m; disp('function z = f(x)');...
disp('z = sin(pi*x) + sin(2*pi*x);');...
diary off;

delete g.m
diary g.m; disp('function z = g(x)');...
disp('z = 0;');...
diary off;

% Remark. f.m g.m finedif.m are used for Algorithm 10.1
f(0); g(0);
pause % Press any key to continue.

clc;
% Place the endpoint of [0,a] in a.

% Place the endpoint of [0,b] in b.

% For the wave equation, enter the constant c.

% Over [0,a] enter the number of grid points n.

% Over [0,b] enter the number of grid points m.

a = 1;
b = 0.5;
c = 2;
n = 11;
m = 11;

U = finedif('f','g',a,b,c,n,m);

pause % Press any key to see the solution.

clc; clg;
Z = fliplr(U);
mesh(Z);...
Mx1='The finite difference solution to the wave equation.';...
title(Mx1);...
shg; pause % Press any key to continue.

W = U';
points = W(:,2:n-1);
clc,echo off,diary output,...
disp(' '),disp(Mx1),disp(' '),disp(points),...
diary off,echo on