Professional Documents
Culture Documents
(b) What will be printed when the following script is executed? Use the specified print format.
Script
a = 3; b = 4;
c = foo(b,a);
fprintf(a is %d\n, a);
fprintf(b is %d\n, b);
fprintf(c is %d\n, c);
Function
function c = foo(d,a)
b = a*2;
c = b+d;
a = d;
fprintf(b is %d\n, b);
Solution:
b
a
b
c
is
is
is
is
6
3
4
10
(b) Let x and n be variables that each stores a positive integer value. Without using the ^ operator
or the equivalent built-in function power, write a fragment below to build a vector z such that z(1)
has the value x, z(2) has the value x2 , z(3) has the value x3 , and so forth. Vector z has length n.
% Assume that scalar variables x and n are initialized to positive integer values.
% Write code to build a vector z as described above.
% Example solution 1
z= ones(1,n);
z(1)= x;
for k= 2:n
z(k)= z(k-1)*x;
end
% Example solution 2
xpow= 1;
for k= 1:n
xpow= xpow*x;
z(k)= xpow;
end
2.5
1.5
0.5
(0,0)
0.5
1.5
2
3
green if the dart is outside both the disk and the blue rectangle
red if the dart is in the part of the disk that does not overlap with the blue rectangle
white if the dart is in the part of the blue rectangle that does not overlap with the disk
black if the dart is in the area where the disk and the blue rectangle overlap
The disk has radius 2 and is centered about (0,0) as marked. You can assume that a dart is never
exactly at the edges of the disk and rectangle.
Reminders: The distance between two points (x1 , y1 ) and (x2 , y2 ) is
command to plot a red asterisk at (3,2) is plot(3,2,r*).
N= 10000;
hit= 0;
for k= 1:N
% Generate pt
x= rand*6-3;
y= rand*5-2;
d= sqrt(x^2 + y^2);
if d<2
if x<1
plot(x,y,r*)
else
plot(x,y,k*)
hit= hit + 1;
end
elseif x>1
plot(x,y,w*)
else
plot(x,y,g*)
end
% in disk
% not in overlap
% in overlap
end
fprintf(Area of overlap is %f \n, ____ hit/N*30 ____ )
4
x;
y + 1;
x + 1;
y;
(b) Implement the following function as specified. For full credit, make effective use of function update
(assume it has been implemented correctly and is accessible).
function [xvec, yvec] = myRandomWalk(x0,y0)
% Simulate a random walk in which only two moves are possible: go north one
% unit or go east one unit. The walk starts at (x0,y0) and in each step, it is
% twice as likely to go east as to go north. The simulation stops after 20
% steps or if the origin (0,0) is reached, whichever happens first.
% Vectors xvec and yvec store the path such that xvec(k) and yvec(k) are the x% and y-coordinates AFTER the kth step. The starting point is NOT stored
% in xvec and yvec, and you can assume that the starting point is not (0,0).
% Example Solution
k= 0; % number of steps so far
x= x0;
y= y0;
while
k<20
&&
(x~=0 || y~=0)
14
10
0
0
10
12
for r= n:-1:1
hold off
6
14
16