11.07.2015 Views

MatlabNotes

MatlabNotes

MatlabNotes

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

-2.0000 3.1416 5.0000-5.0000 -3.0000 -1.0000>> x > 3 & x < 4ans =0 1 00 0 0>> x > 3 | x == -3ans =0 1 10 1 0As one might expect, & represents and and (notso clearly) the vertical bar | means or; also ~means not as in ~= (not equal), ~(x>0), etc.>> x > 3 | x == -3 | x > x, L = x >= 0x =-2.0000 3.1416 5.0000-5.0000 -3.0000 -1.0000L =0 1 10 1 1>> pos = x.*Lpos =0 3.1416 5.00000 0 0so the matrix pos contains just those elementsof x that are non–negative.>> x = 0:0.05:6; y = sin(pi*x);>> Y = (y>=0).*y;>> plot(x,y,’:’,x,Y,’-’ )20.1 While LoopsThere are some occasions when we want to repeata section of Matlab code until some logicalcondition is satisfied, but we cannot tell in advancehow many times we have to go aroundthe loop. This we can do with a while...endconstruct.Example 20.1 What is the greatest value of nthat can be used in the sum1 2 +2 2 + ···+ n 2and get a value of less than 100?>> S = 1; n = 2;>> while S+ n^2 < 100S = S + n^2; n = n+1;end>> [n-1, S]ans =6 91The lines of code between while and end willonly be executed if the condition S+n^2 < 100is true.Exercise 20.1 Replace 100 in the previous exampleby 10 and work through the lines of codeby hand. You should get the answers n =2andS =5.Exercise 20.2 Type the code from Example20.1into a script–file named WhileSum.m (See §10.)A more typical example isExample 20.2 Find the approximate value ofthe root of the equation x = cos x. (SeeExample13.1.)We may do this by making a guess x 1 = ⇡/4,say, then computing the sequence of valuesx n = cos x n 1 , n =2, 3, 4,...and continuing until the di↵erence, d, betweentwo successive values |x n x n 1 | is small enough.29

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

Saved successfully!

Ooh no, something went wrong!