Example of projection onto an orthogonal set

1 Find the projection of $\sin x$ onto the orthogonal set $\{1,\cos x, \cos 2x\}$ on $[0,\pi]$.

2 Find the distance from $\sin x$ to its projection.

3 Plot the function and its projection on the same axes.

Contents

Step 1

Compute the necessary inner product of $\sin x$ with each of the functions in the orthogonal set.

Here is $\langle \sin(x),1\rangle$.

syms x
ip1 = int(sin(x),x,0,sym(pi))
 
ip1 =
 
2
 

Here is $\langle \sin(x),\cos x\rangle$.

ip2 = int(sin(x)*cos(x),x,0,sym(pi))
 
ip2 =
 
0
 

Here is $\langle \sin(x),\cos 2x\rangle$.

ip3 = int(sin(x)*cos(2*x),x,0,sym(pi))
 
ip3 =
 
-2/3
 

Step 2

Compute the necessary lengths.

$||1||^2$ is

n1 = int(1,0,sym(pi))
 
n1 =
 
pi
 

$||\cos 2x||^2$ is

n3 = int((cos(2*x))^2,0,sym(pi))
 
n3 =
 
pi/2
 

Step 3

Write down the Fourier coefficients.

c1 = ip1/n1
 
c1 =
 
2/pi
 
c2 = 0
c2 =

     0

c3 = ip3/n3
 
c3 =
 
-4/(3*pi)
 

Step 4

The projection is

proj = c1*1+c2*cos(x)+c3*cos(2*x)
 
proj =
 
2/pi - (4*cos(2*x))/(3*pi)
 
pretty(proj)
  2    4 cos(2 x)
  -- - ----------
  pi      3 pi

Step 5

The distance squared is

$$
||\sin(x)||^2 \mbox{--}\left( \frac{\langle \sin x ,1 \rangle}{||1||^2} +\frac{
\langle \sin x ,\cos 2x\rangle}{||\cos 2x||^2}\right)
$$

which is

distsq = int((sin(x))^2,0,sym(pi)) - (ip1^2/n1 + ip3^2/n3)
 
distsq =
 
pi/2 - 44/(9*pi)
 

so the distance is

dist = sqrt(distsq)
 
dist =
 
(pi/2 - 44/(9*pi))^(1/2)
 

which is approximately

vpa(dist,8)
 
ans =
 
0.12089111
 

Step 6

Plot $\sin x$ and its projection.

I'll use plot so I can control the color and the thickness. To use plot I will turn the projection into a vectorized function and I need a vector on which to evaluate the functions I'm plotting.

X = 0:.001:pi;
Proj = inline(vectorize(proj))
plot(X,sin(X),'linewidth',2)
hold on
plot(X,Proj(X),'color','g','linewidth',2)
hold off
axis equal
axis([0 pi 0 1.1])
Proj =

     Inline function:
     Proj(x) = 2./pi - (4.*cos(2.*x))./(3.*pi)