12.07.2015 Views

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

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.

X = QUADRATIC(A,B,C) returns the two roots <strong>of</strong> thequadratic equationy = A*x^2 + B*x + C.The roots are contained in X = [X1 X2].matlab only echoes the comment lines that are contiguous; the first noncommentline, in this case the blank line before the signature, tells matlabthat the help comments have ended. The first line <strong>of</strong> the help commentsis searched <strong>and</strong>, if successful, displayed when you type a lookforcomm<strong>and</strong>.Comment lines can appear anywhere in the body <strong>of</strong> an m-file. Commentscan be put at the end <strong>of</strong> a line <strong>of</strong> code:rootdisc = sqrt(b.^2 - delta); % Root <strong>of</strong> the discriminantBlank lines can appear anywhere in the body <strong>of</strong> an m-file. Apart fromending the help comment lines in a function, blank lines are ignored.8.3 Flow Controlmatlab has four kinds <strong>of</strong> statements you can use to control the flowthrough your code:if, else <strong>and</strong> elseif execute statements based on a logical testswitch, case <strong>and</strong> otherwise execute groups <strong>of</strong> statements based ona logical testwhile <strong>and</strong> end execute statements an indefinite number <strong>of</strong> times,based on a logical testfor <strong>and</strong> end execute statements a fixed number <strong>of</strong> timesIf, Else, ElseifThe basic form <strong>of</strong> an if statement is:if teststatementsendThe test is an expression that is either 1 (true) or 0 (false). Thestatements between the if <strong>and</strong> end statements are executed if thetest is true. If the test is false the statements will be ignored <strong>and</strong>execution will resume at the line after the end statement. The testexpression can be a vector or matrix, in which case all the elementsmust be equal to 1 for the statements to be executed. Further testscan be made using the elseif <strong>and</strong> else statements.Exercise 2 Write a function m-file that takes a vector input <strong>and</strong>returns 1 if all <strong>of</strong> the elements are positive, −1 if they are all negative,<strong>and</strong> zero for all other cases. Hint: Type help all. (Answeron page 183.)c○ 2000 by CRC Press LLC

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

Saved successfully!

Ooh no, something went wrong!