====== Differences ====== This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
gibson:teaching:fall-2014:math445:lecture9-diary [2014/10/13 19:48] gibson [for loops] |
gibson:teaching:fall-2014:math445:lecture9-diary [2014/10/15 12:45] (current) gibson [example: solving a nonlinear equation] |
||
---|---|---|---|
Line 7: | Line 7: | ||
A ''for'' loop repeats a given action a fixed number of times. The general form of a ''for'' loop is | A ''for'' loop repeats a given action a fixed number of times. The general form of a ''for'' loop is | ||
<code matlab> | <code matlab> | ||
- | for value = vector | + | for value = vector |
- | action | + | action |
- | end | + | end |
</code> | </code> | ||
The ''action'' will be performed ''length(vector)'' times, with ''value'' set to each element of | The ''action'' will be performed ''length(vector)'' times, with ''value'' set to each element of | ||
Line 30: | Line 30: | ||
**example 3:** Write a ''mysum'' function that computes the sum of the elements of a vector. | **example 3:** Write a ''mysum'' function that computes the sum of the elements of a vector. | ||
+ | <code matlab> | ||
+ | function s = mysum(x) | ||
+ | % return the sum of the components of vector x | ||
+ | | ||
+ | s = 0; % start with partial sum s = 0 | ||
+ | for i = 1:length(x) % loop over all elements in x | ||
+ | s = s + x(i); % add x(i) to the previously computed partial sum | ||
+ | end | ||
+ | | ||
+ | end | ||
+ | </code> | ||
**example 4:** Write a function that computes the factorial of //n//. | **example 4:** Write a function that computes the factorial of //n//. | ||
- | **The for loop is probably the single most important programming construct in numerical mathematics.** | + | <code matlab> |
+ | function p = factorial(n) | ||
+ | % return the factorial of n (assume n is a positive integer) | ||
+ | |||
+ | p = 1; % start with partial product p = 1 | ||
+ | for k = 1:n % loop k over all integers from 1 to n | ||
+ | p = p*k; % multiply previous partial product by k | ||
+ | end | ||
+ | |||
+ | end | ||
+ | </code> | ||
+ | **The for loop is probably the single most important programming construct in numerical mathematics.** | ||
===== while loops ===== | ===== while loops ===== | ||
Line 40: | Line 62: | ||
A ''while'' loop repeats a given action as long as its condition is true. The general form is | A ''while'' loop repeats a given action as long as its condition is true. The general form is | ||
<code matlab> | <code matlab> | ||
- | while condition | + | while condition |
- | action | + | action |
- | end | + | end |
</code> | </code> | ||
+ | In order for the ''while'' loop to terminate, the action must modify variables in the condition. | ||
+ | For example, the factorial function above could also be written this way... | ||
+ | |||