11.07.2015 Views

MatlabNotes

MatlabNotes

MatlabNotes

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Method 1:>> x = zeros(1,20); x(1) = pi/4;>> n = 1; d = 1;>> while d > 0.001n = n+1; x(n) = cos(x(n-1));d = abs( x(n) - x(n-1) );endn,x(1:n)n =14x =Columns 1 through 60.7854 0.7071 0.7602 0.7247 0.7487 0.7326Columns 7 through 120.7435 0.7361 0.7411 0.7377 0.7400 0.7385Columns 13 through 140.7395 0.7388There are a number of deficiencies with thisprogram. The vector x stores the results ofeach iteration but we don’t know in advancehow many there may be. In any event, we arerarely interested in the intermediate values ofx, only the last one. Another problem is thatwe may never satisfy the condition d apple 0.001,in which case the program will run forever, sowe should place a limit on the maximum numberof iterations.Incorporating these improvements leads toMethod 2:>> xold = pi/4; n = 1; d = 1;>> while d > 0.001 & n < 20n = n+1; xnew = cos(xold);d = abs( xnew - xold );xold = xnew;end>> [n, xnew, d]ans =14.0000 0.7388 0.0007We continue around the loop so long as d>0.001 and n0.0001, and thisgives>> [n, xnew, d]ans =19.0000 0.7391 0.0001from which we may judge that the root requiredis x =0.739 to 3 decimal places.The general form of while statement iswhile a logical testCommands to be executedwhen the condition is trueend20.2 if...then...else...endThis allows us to execute di↵erent commandsdepending on the truth or falsity of some logicaltests. To test whether or not ⇡ e is greater than,or equal to, e ⇡ :>> a = pi^exp(1); c = exp(pi);>> if a >= cb = sqrt(a^2 - c^2)endso that b is assigned a value only if a c. Thereis no output so we deduce that a = ⇡ e > if a >= cb = sqrt(a^2 - c^2)elseb = 0endb =0which ensures that b is always assigned a valueand confirming that a> if a >= cb = sqrt(a^2 - c^2)elseif a^c > c^ab = c^a/a^celseb = a^c/c^aendb =0.2347Exercise 20.3 Which of the above statementsassigned a value to b?The general form of the if statement is30

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

Saved successfully!

Ooh no, something went wrong!