15.11.2014 Views

Chapter 4: Programming in Matlab - College of the Redwoods

Chapter 4: Programming in Matlab - College of the Redwoods

Chapter 4: Programming in Matlab - College of the Redwoods

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

330 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />

We draw <strong>the</strong> square <strong>in</strong> counterclockwise order <strong>of</strong> vertices, start<strong>in</strong>g at <strong>the</strong><br />

po<strong>in</strong>t (1, 1). In that order, we set <strong>the</strong> x- and y-values <strong>of</strong> <strong>the</strong> vertices <strong>in</strong> <strong>the</strong> vectors<br />

x and y. We <strong>the</strong>n draw <strong>the</strong> square with a thickened l<strong>in</strong>e width and color it dark<br />

blue.<br />

x=[1,-1,-1,1,1]; y=[1,1,-1,-1,1];<br />

l<strong>in</strong>e(x,y,’L<strong>in</strong>eWidth’,2,’Color’,[0,0,0.625])<br />

Next, we set <strong>the</strong> number <strong>of</strong> darts thrown at 1000. Then we plot one dart<br />

at <strong>the</strong> orig<strong>in</strong>, change its l<strong>in</strong>estyle to ’none’ (po<strong>in</strong>ts will not be connected with l<strong>in</strong>e<br />

segements), choose a marker style, and color it dark blue.<br />

N=1000;<br />

dart=l<strong>in</strong>e(0,0,...<br />

’L<strong>in</strong>eStyle’,’none’,...<br />

’Marker’,’.’,...<br />

’Color’,[0,0,0.625]);<br />

In <strong>the</strong> loop that follows, we use <strong>the</strong> handle to this <strong>in</strong>itial dart to add x- and<br />

y-data (additional darts). First, we set <strong>the</strong> number <strong>of</strong> hits (darts that land <strong>in</strong>side<br />

<strong>the</strong> circle) to zero (we don’t count <strong>the</strong> <strong>in</strong>itial dart at (0, 0)).<br />

hits=0;<br />

for k=1:N<br />

x=2*rand-1;<br />

y=2*rand-1;<br />

set(dart,...<br />

’XData’,[get(dart,’XData’),x],...<br />

’YData’,[get(dart,’YData’),y])<br />

%drawnow<br />

if (x^2+y^2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!