{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

12 Iteration

12 Iteration - 12 Iteration Iteration vs Recursion Any...

Info icon This preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Iteration - 1 12 - Iteration Iteration vs. Recursion Any problem that can be solved recursively can also be solved iteratively . In recursion, you start at the end of a problem and work backward until you get to your base case. With iteration, you start at the base case and work forward. Recursive programs have to have many copies of themselves “open” at a time. Iterative programs do not. They just loop until they reach the solution. So, although it often takes more thought to come up with an iterative program than a recursive one, the iterative solution is often faster and uses less memory. In any case, a good programmer needs to know how to think both ways. As a rule of thumb: a recursive function is a function that calls itself. An iterative function just loops. Iteration In the simplest case iteration is a for loop. Suppose for example, we want to compute the dot product of two row vectors a and b . A MATLAB function to do this is: %dotprod.m %calculates the dot product of two row vectors %E77 reader %07-01 D# function [sum] = dotprod(a, b) sum = 0; for i = 1:length(a) sum = sum + a(i) * b(i); end The inner loop goes through a and b one by one as i takes on the values 1:length(a).
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Iteration - 2 Matrix Multiply
Image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern