Graphics Programs Reference
In-Depth Information
if s <= 0.339
r=1;
else
r=0;
end
We can simulate a year in Tony's career by evaluating the script M-file
atbat 500 times. The following program does exactly that. Then it
computes his average by adding up the number of hits and dividing by
the number of at bats, that is, 500. We build in a variable that allows for
a varying number of at bats in a year, although we shall only use 500.
function y = yearbattingaverage(n)
%This function file computes Tony's batting average for
%a single year, by simulating n at bats, adding up the
%number of hits, and then dividing by n.
X = zeros(1, n);
for i = 1:n
atbat;
X(i) = r;
end
y = sum(X)/n;
yearbattingaverage(500)
ans =
0.3200
(b)
Now let's write a function M-file that simulates a 20-year career. As with
the number of at bats in a year, we'll allow for a varying length career.
function y = career(n,k)
%This function file computes the batting average for each
%year in a k-year career, asuming n at bats in each year.
%Then it lists the maximum, minimum, and lifetime average.
Y = zeros(1, k);
for j = 1:k
Y(j) = yearbattingaverage(n);
end
Search WWH ::




Custom Search