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

Info iconThis 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) s u m=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
Background image of page 1

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

View Full DocumentRight Arrow Icon
Iteration - 2 Matrix Multiply Matrix multiplication can easily be programmed iteratively using three nested
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/12/2011 for the course E 7 taught by Professor Patzek during the Spring '08 term at University of California, Berkeley.

Page1 / 4

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

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online