Chapter 4 Loops

Download Report

Transcript Chapter 4 Loops

Chapter 8
Loops
For Loop
>Executes a block of statements
a specified number of times.
Form:
for loop variable=first:incr:last
statements
end
For Loop Example
Calculate the factorials for
positive values of n.
n! = n * (n-1)*…* 3 * 2 *1
0! = 1
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.
While Loop
>Executes a block of statements
indefinitely as long as some
condition is satisfied.
Form:
while logical expression
statements
end
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 Example
Design code that will
read in a set of
measurements (data)
and calculate the mean
& standard deviation of
the input data set.
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.
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 Break
for k = 1:10
x=50 – k^2;
if x < 0
break
end
y=sqrt(x)
end
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
Regression Analysis
Investigation of the
relationship between two or
more variables related in a
non-deterministic fashion.
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.
Least Squares Method Calculations
Slope:
a = (xy) – (x)y
2
(x ) – (x)x
y-intercept:
b=y–ax
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.