Upload
egbert-montgomery
View
219
Download
0
Embed Size (px)
DESCRIPTION
For Loop Example Calculate the factorials for positive values of n. n! = n * (n-1)*…* 3 * 2 *1 0! = 1
Citation preview
Chapter 8 Loops
For Loop >Executes a block of statements a specified number of times.
Form: for loop variable=first:incr:last
statementsend
For Loop ExampleCalculate the factorials for positive values of n.
n! = n * (n-1)*…* 3 * 2 *10! = 1
For Loop ExampleDesign code that will read in a set of measurements (data) and calculate the mean & standard deviation of the input data set.
While Loop >Executes a block of statements indefinitely as long as some condition is satisfied.
Form: while logical expression
statementsend
Example While Loop>>x=5;>>while x<25>> Disp(x)>> x=2*x – 1;>>end
Example While Loop>>k=1; b=-2; x= -1; y=-2;>>while k<=3>> k, b, x, y>> y=x^2 – 3;>> if y < b>> b=y;>> end>> x=x+1;>> k=k+1;>>end
While Loop ExampleDesign code that will read in a set of measurements (data) and calculate the mean & standard deviation of the input data set.
While Loop ExampleUse a While Loop to determine how long it will take to accumulate $1,000,000 in a bank account if you deposit $10,000 initially and $10,000 at the end of each year. Assume 6% annual interest.
Loop Control Statements> Break
Terminates execution of the loop. Control goes to end. > Continue
Terminates only the current iteration. Control goes to the top of the loop.
Example Breakfor k = 1:10 x=50 – k^2; if x < 0 break end y=sqrt(x)end
Example Continuex= [10, 1000, -10, 100]y=NaN*x;for k=1:length(x) if x(k) < 0 continue end y(k)=log10(x(k));endy
Regression Analysis Investigation of the relationship between two or more variables related in a non-deterministic fashion.
Least Squares MethodThe best fit is the one that minimizes the sum of the squares of the vertical differences between the line and the data points.
Least Squares Method CalculationsSlope:
a = (xy) – (x)y (x2) – (x)x
y-intercept:b = y – a x
Least-Squares ExampleWrite a program that will calculate the least-squares slope and y-axis intercept for a given set of noisy measured data points(x,y). The data points can be read from the keyboard.