clear
clc
% choice = input('Call it, heads(h) or tails(t):, 's');
choice =
't'
;
% Example: the input command doesn't publish well
flip = randi(2);
% Will produce a 1 or 2 to indicate heads or tails
if
(choice==
'h'
) && (flip==1)
disp(
'Heads, you win!'
)
elseif
(choice==
'h'
) && (flip==2)
disp(
'Tails, you lose.'
)
elseif
(choice==
't'
) && (flip==2)

Homework 2 Solutions
2
disp(
'Tails, you win!'
)
elseif
(choice==
't'
) && (flip==1)
disp(
'Tails, you lose.'
)
else
disp(
'Was that heads or tails? You lose.'
)
end
Tails, you lose.
Problem 3 - ThankYou.m
Prints the repeated phrase "Thank You" and shifts the phrase to the right for each line.
clear
clc
for
k = 0:5
disp([blanks(k)
'Thank You!'
])
end
Thank You!
Thank You!
Thank You!
Thank You!
Thank You!
Thank You!
Problem 4 - PiSeries.m
Approximates the value of pi using an arithmatic series with N terms, where the terms will be summed
over the series.
clear
clc
N = 1*10^6;
piApprox = 0;
% Initialize accumulator, pi
for
k=0:N
piApprox = piApprox + 4*(-1)^k/(2*k + 1);
end
disp([
'Approximate value of pi for N='
, num2str(N),
...
' is '
, num2str(piApprox, 8)]);
Approximate value of pi for N=1000000 is 3.1415937
Problem 5 - PiSeriesMultiple.m
Alter the previous program so that it uses an outer for loop to display the approximate value of pi for for
N=1 to N=10^7
clear
clc
for
N = [1 10 100 1000 10000 100000 1000000 10000000];
piApprox = 0;
% Initialize accumulator, pi

#### You've reached the end of your free preview.

Want to read all 5 pages?

- Fall '14
- Mean, .........