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:51] gibson [for loops] | gibson:teaching:fall-2014:math445:lecture9-diary [2014/10/15 12:45] (current) gibson [example: solving a nonlinear equation] | ||
|---|---|---|---|
| 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//. | ||
| + | |||
| + | <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.** | **The for loop is probably the single most important programming construct in numerical mathematics.** | ||
| - | |||
| ===== while loops ===== | ===== while loops ===== | ||
| Line 48: | Line 70: | ||
| For example, the factorial function above could also be written this way... | For example, the factorial function above could also be written this way... | ||
| + | |||