Download presentation
Presentation is loading. Please wait.
Published byEgbert Montgomery Modified over 9 years ago
1
Chapter 8 Loops
2
For Loop >Executes a block of statements a specified number of times. Form: for loop variable=first:incr:last statements end
3
For Loop Example Calculate the factorials for positive values of n. n! = n * (n-1)*…* 3 * 2 *1 0! = 1
4
For Loop Example Design code that will read in a set of measurements (data) and calculate the mean & standard deviation of the input data set.
5
While Loop >Executes a block of statements indefinitely as long as some condition is satisfied. Form: while logical expression statements end
6
Example While Loop >>x=5; >>while x > Disp(x) >> x=2*x – 1; >>end
7
Example While Loop >>k=1; b=-2; x= -1; y=-2; >>while k > k, b, x, y >> y=x^2 – 3; >> if y > b=y; >> end >> x=x+1; >> k=k+1; >>end
8
While Loop Example Design code that will read in a set of measurements (data) and calculate the mean & standard deviation of the input data set.
9
While Loop Example Use 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.
10
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.
11
Example Break for k = 1:10 x=50 – k^2; if x < 0 break end y=sqrt(x) end
12
Example Continue x= [10, 1000, -10, 100] y=NaN*x; for k=1:length(x) if x(k) < 0 continue end y(k)=log10(x(k)); end y
13
Regression Analysis Investigation of the relationship between two or more variables related in a non-deterministic fashion.
14
Least Squares Method The best fit is the one that minimizes the sum of the squares of the vertical differences between the line and the data points.
15
Least Squares Method Calculations Slope: a = ( xy) – ( x)y ( x 2 ) – ( x)x y-intercept: b = y – a x
16
Least-Squares Example Write 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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.