Presentation is loading. Please wait.

Presentation is loading. Please wait.

EGR 106 – Week 7 – Functions Function concept and an example Rules for functions Local and global variables More examples Errors Application: zeroes and.

Similar presentations


Presentation on theme: "EGR 106 – Week 7 – Functions Function concept and an example Rules for functions Local and global variables More examples Errors Application: zeroes and."— Presentation transcript:

1 EGR 106 – Week 7 – Functions Function concept and an example Rules for functions Local and global variables More examples Errors Application: zeroes and minima of equations Textbook chapter 6, pages 139-149

2 Function concept So far: – Have used Matlab’s built-in functions – Have written scripts Function ≡ reusable script – Sometimes called a subprogram – Building block for larger programs Example: converting degrees to radians

3 Example Function: DEG2RAD

4 Rules for Functions First line of the file must be of the form: function [outputs] = name(inputs) Identifies a function file List of function result variables List of any variables that the function needs Name of the function and the file (name.m)

5 Variables: Local vs Global Usually, once created, variables are available in the workspace until cleared Functions create their own workspace with their own local variables distinct from those in the original workspace – Functions cannot change variables within the original workspace – except through outputs – Exception – global variables can span both workspaces and be manipulated in both

6 Example Functions function a = tri_area(b,h) % TRI_AREA area of a right triangle % TRI_AREA(B,H) returns the area of % a right triangle with base B and height H a = 0.5*b.*h;

7 function [a,p] = triangle(b,h) % TRIANGLE area/perimeter calculation %[A,P] =TRIANGLE(B,H) returns the % area (A) and perimeter (P) of a % right triangle with base B %and height H a = 0.5*b.*h; p = b + h + sqrt(b.^2+h.^2);

8 Typical Errors Too few inputs

9 Too many inputs Too many outputs Wrong input type – funny result

10 Problem 3 % The function polyder([a b c]) can be used % to determine the derivative of the quadratic % function. The coordinates of the maximum % or minimum are found by finding the roots % of the derivative of the polynomial using the % function roots. x = roots(polyder([ a b c])); y = a*x^2 + b*x + c;


Download ppt "EGR 106 – Week 7 – Functions Function concept and an example Rules for functions Local and global variables More examples Errors Application: zeroes and."

Similar presentations


Ads by Google