Skip to main content
Mathematics LibreTexts

26.2: Understanding Projections With Code

  • Page ID
    69417
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    In this in-class assignment, we are going to avoid some of the more advanced libraries ((i.e. no numpy or scipy or sympy) to try to get a better understanding about what is going on in the math. The following code implements some common linear algebra functions:

    #Standard Python Libraries only
    import math
    import copy
    
    from urllib.request import urlretrieve
    urlretrieve('https://raw.githubusercontent.com/colbrydi/jupytercheck/master/answercheck.py', 
                'answercheck.py');
    def dot(u,v):
        '''Calculate the dot product between vectors u and v'''
        temp = 0;
        for i in range(len(u)):
            temp += u[i]*v[i]
        return temp
    def multiply(m1,m2):
        '''Calculate the matrix multiplication between m1 and m2 represented as list-of-list.'''
        n = len(m1)
        d = len(m2)
        m = len(m2[0])
        
        if len(m1[0]) != d:
            print("ERROR - inner dimentions not equal")
        result = [[0 for i in range(n)] for j in range(m)]
        for i in range(0,n):
            for j in range(0,m):
                for k in range(0,d):
                    result[i][j] = result[i][j] + m1[i][k] * m2[k][j]
        return result
    def add_vectors(v1,v2):
        v3 = []
        for i in range(len(v1)):
            v3.append(v1[i]+v2[i])
        return v3
    def sub_vectors(v1,v2):
        v3 = []
        for i in range(len(v1)):
            v3.append(v1[i]-v2[i])
        return v3
    def norm(u):
        '''Calculate the norm of vector u'''
        nm = 0
        for i in range(len(u)):
            nm += u[i]*u[i]
        return math.sqrt(nm)
    def transpose(A):
        '''Calculate the transpose of matrix A represented as list of lists'''
        n = len(A)
        m = len(A[0])
        AT = list()
        for j in range(0,m):    
            temp = list()
            for i in range(0,n):
                temp.append(A[i][j])
            AT.append(temp)
        return AT

    Projection function

    Do This

    Write a function that projects vector \(v\) onto vector \(u\). Do not use the numpy library. Instead use the functions provided above:

    \[\mbox{proj}_u v = \frac{v \cdot u}{u \cdot u} u \nonumber \]

    Make sure this function will work for any size of \(v\) and \(u\).

    def proj(v,u):
        ## Put your code here
        return pv

    Let’s test your function. Below are two example vectors. Make sure you get the correct answers. You may want to test this code with more than one set of vectors.

    u = [1,2,0,3]
    v = [4,0,5,8]
    print(proj(u,v))
    from answercheck import checkanswer
    
    checkanswer.vector(proj(u,v),'53216508af49c616fa0f4e9676ce3b9d');

    Visualizing projections

    Do This

    See if you can design and implement a small function that takes two vectors (\(a\) and \(b\)) as inputs and generates a figure similar to the one above.

    I.e. a black line from the origin to “\(b\)”, a black line from origin to “\(a\)”; a green line showing the “\(a\)” component in the “\(b\)” direction and a red line showing the “\(a\)” component orthogonal to the green line. Also see section titled “Projection of One Vector onto Another Vector” in Section 4.6 on page 258 of the book.

    When complete, show your solution to the instructor.

    %matplotlib inline
    import matplotlib.pylab as plt
    
    b = [3,2]
    a = [2,3]
    
    def show_projection(a,b):
        plt.plot([0,a[0]], [0,a[1]], color='black')
        plt.annotate('b', b, 
                xytext=(0.9, 0.7), textcoords='axes fraction',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='right', verticalalignment='top')
        plt.annotate('a', a, 
                xytext=(0.7, 0.95), textcoords='axes fraction',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='right', verticalalignment='top')
        plt.plot([0,b[0]], [0,b[1]], color='black')
        
    #Finish your code here
    
        plt.axis('equal')
        
    x = show_projection(a,b) ;

    This page titled 26.2: Understanding Projections With Code is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Dirk Colbry via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

    • Was this article helpful?