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.

6 8 0 1>> k = find(A==0)k =29Thus, we find that A has elements equal to 0 inpositions 2 and 9. To interpret this result wehave to recognize that “find” first reshapes Ainto a column vector (see §15.1)—this is equivalentto numbering the elements of A by columnsas in1 4 7 102 5 8 113 6 9 12>> n = find(A > A(n)ans =-20-10Thus, n gives a list of the locations of the entriesin A that are apple 0 and then A(n) gives us thevalues of the elements selected.>> m = find( A’ == 0)m =511Since we are dealing with A’, the entries arenumbered by rows.22 Function m–filesWe can extend the number of Matlab built-infunctions by writing our own. They are specialcases of m–files (§7).Example 22.1 The area, A, of a triangle withsides of length a, b and c is given byA = p s(s a)(s b)(s c),where s =(a+b+c)/2. Write a Matlab functionthat will accept the values a, b and c as inputsand return the value of A as output.The main steps to follow when defining a Matlabfunction are:1. Decide on a name for the function, makingsure that it does not conflict with aname that is already used by Matlab. Inthis example the name of the function isto be area, so its definition will be savedin a file called area.m2. The first line of the file must have theformat:function [list of outputs]= function name(list of inputs)For our example, the output (A)isafunctionof the three variables (inputs) a, band c so the first line should readfunction [A] = area(a,b,c)3. Document the function. That is, describebriefly the purpose of the function andhow it can be used. These lines should bepreceded by % which signify that they arecomment lines that will be ignored whenthe function is evaluated.4. Finally include the code that defines thefunction. This should be interspersed withsu cient comments to enable another userto understand the processes involved.The complete file might look like:function [A] = area(a,b,c)% Compute the area of a triangle whose% sides have length a, b and c.% Inputs:% a,b,c: Lengths of sides% Output:% A: area of triangle% Usage:% Area = area(2,3,4);% Written by dfg, Oct 14, 1996.s = (a+b+c)/2;A = sqrt(s*(s-a)*(s-b)*(s-c));%%%%%%%%% end of area %%%%%%%%%%%33

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

Saved successfully!

Ooh no, something went wrong!