Lecture 6 2 PDF

Title Lecture 6 2
Author Kev Liu
Course Engineering Computing
Institution University of Sydney
Pages 61
File Size 774.3 KB
File Type PDF
Total Downloads 60
Total Views 139

Summary

dds...


Description

ENGG1801 Engineering Computing Lecture 6-2 Functions (2) Semester 1, 2017 School of Information Technologies The University of Sydney, Australia sydney.edu.au/engineering/it/courses/engg1801 Jason Chan [email protected] ENGG1801 Engineering Computing Jason Chan

1

Semester 1, 2017 Schedule Part 1 – Excel Part 2 – Matlab Basics

Week

Date

1

6 – 10 Mar

Introduction, Excel basics

2

13 – 17 Mar

Functions, Plots, Solving equations, File I/O

3

20 – 24 Mar

Matrix algebra

4

27 – 31 Mar

Matlab basics, If statements, Arrays

5

3 – 7 Apr

6

10 – 14 Apr

Lecture topics

Notice

Lab Exam 1 (5%), No Wednesday lecture

Loops No Friday labs (Good Friday holiday), Extra “Lab 6’s” on Wednesday

Functions Mid-Semester Break

No Tuesday lecture (ANZAC Day holiday), Extra “Lab 6’s” on Monday - Thursday

Part 3 – Matlab Applications

7

24 – 28 Apr

Functions

8

1 – 5 May

Character strings, Text & File I/O

9

8 – 12 May

2-D and 3-D plotting, Surface plots

10

15 – 19 May

Matrix algebra

11

22 – 26 May

Images, Movies

12

29 May – 2 Jun

13

5 – 9 Jun

Interpolation and curve fitting Help for the Final Exam

Lab Exam 2 (20%)

No Tuesday lecture Lab Exam 3 (20%), No Tuesday lecture

Student vacation (stuvac) Exam

19 – 30 Jun

---

ENGG1801 Engineering Computing Jason Chan

Final Exam (50%)

2

What will I learn today? • Functions – More about functions so that they can give values that can be used in other parts of the program

ENGG1801 Engineering Computing Jason Chan

3

Consider this Question…

Does this function make sense? Is it written correctly? f(n) = 3n + 2

ENGG1801 Engineering Computing Jason Chan

11

Consider this Question…

What is the value of n in this function? And what is the specific value of f(n)? f(n) = 3n + 2

ENGG1801 Engineering Computing Jason Chan

12

It depends on what we give it… • The function is a general case • n can have many values, depending on what specific value we give it when we use it: f(2) or f(-1) etc… • Same with functions in Matlab: Parameters are NOT given values inside the function. They are given values when the function is used ENGG1801 Engineering Computing Jason Chan

13

Consider this Question… What is the value of n in this function? function print1toN(n) for i = 1:n disp(i); end end

ENGG1801 Engineering Computing Jason Chan

14

Consider this Question… n has no value! Does this function make sense? function print1toN(n) for i = 1:n disp(i); end end

ENGG1801 Engineering Computing Jason Chan

15

Parameters / Arguments function print1toN(n) for i = 1:n disp(i); end end

• This function is written correctly • The value of the parameter n is given when the function is used, it is NOT given a value inside of the function ENGG1801 Engineering Computing Jason Chan

16

Parameters / Arguments • We need to give the parameter value when we use the function like this: % Print the integers 1 to 4 maxNumber = 4; print1toN(maxNumber);

• This code belongs in another file, and goes outside of the function we are using ENGG1801 Engineering Computing Jason Chan

17

Consider this Question… Just looking at this function, what specific numbers will this function print? function print1toN(n) for i = 1:n disp(i); end end

ENGG1801 Engineering Computing Jason Chan

18

General vs Specific Case • Our functions should work in the general case, for any input value we give it • When we use a function, we then have to use it in a specific case • That’s why we have parameters – the function can be used with different (and specific) input values, and the function behaves differently depending on the specific input value given ENGG1801 Engineering Computing Jason Chan

19

Consider this Question… Can you see what is wrong with this function? function print1toN(n) n = 4; for i = 1:n disp(i); end end

ENGG1801 Engineering Computing Jason Chan

20

General vs Specific Case • On the previous slide, the function only works for a specific case, because in the function, the parameter value was set to a specific value (4) when we wrote: n = 4;

• Parameter values are supposed to be given when the function is used, NOT inside the function ENGG1801 Engineering Computing Jason Chan

21

General vs Specific Case • So now if we use the previous function (which has something wrong) like this: % Try to print the integers 1 to 6, % but it will only print 1 to 4 because % the function has been written to only % work in a specific case maxNumber = 6; print1toN(maxNumber);

the function only prints the integers 1 to 4 ENGG1801 Engineering Computing Jason Chan

22

Passing data into / out of a function • We have learnt how to use parameters to pass data into a function • But how do we get a function to pass data out of the function? • Remember the problem of variable scope (lecture 6-1) means that a variable created in a function cannot be seen outside of that function ENGG1801 Engineering Computing Jason Chan

23

This doesn’t work • So if we write the function like this: % This function squares the given number % (multiplies given number by itself), % but the result cannot be seen outside % of the function function squareBad(n) result = n*n; end

ENGG1801 Engineering Computing Jason Chan

24

This doesn’t work • We can’t get the result like this: % Try to calculate 4 squared number = 4; squareBad(number); % This gives an error message, because % the variable 'result' can only be seen % inside the function disp(result);

ENGG1801 Engineering Computing Jason Chan

25

This doesn’t work • When we run the previous code (saved in variableScopeDemo5.m), we get this error message:

ENGG1801 Engineering Computing Jason Chan

26

This also doesn’t work • The function below also doesn’t work, because it only prints onto the screen: function squareBad2(n) result = n*n; disp(result); end

• It does not give back a value / result that can be used elsewhere in the program ENGG1801 Engineering Computing Jason Chan

27

Functions in maths • In maths, a function has a result or value, and it can be used like this: f(n) = 3n + 2

y = f(2) + 2xf(1) = [3x2+2] + 2x[3x1+2] = 18 • We would like to do the same in programs • Our functions should be able to give back a value or result that can be used somewhere else in the program ENGG1801 Engineering Computing Jason Chan

28

Example of what we want • We want to use the function like this: % Calculate 4 squared using a function, % and store the result in a variable % which can be used later in the program % (such as to print, or use it in % another calculation) number = 4; result = square(number); disp(result);

ENGG1801 Engineering Computing Jason Chan

29

This still doesn’t work • But the way we have been writing functions so far wont work: function squareBad(n) result = n*n; end

ENGG1801 Engineering Computing Jason Chan

30

Returning values from functions • We need to tell Matlab that we want this function to return (or given back) a value, like this: function result = square(n) result = n*n; end

ENGG1801 Engineering Computing Jason Chan

31

Returning values from functions

• We do this by putting a variable name and the = sign on the left of the function name • Whatever value this variable has when the function is finished is returned (given back) to the code that called (used) this function ENGG1801 Engineering Computing Jason Chan

32

Using returned values • Now we can use the function as much as we want, with different values each time: % Use a function that returns to us a value number = 4; result1 = square(number); disp(result1); % Let's use the function again in a different way result2 = square(5); disp(result2); % And yet another different way disp(square(6)); ENGG1801 Engineering Computing Jason Chan

33

Using returned values • We can assign the returned value from the function to a variable

ENGG1801 Engineering Computing Jason Chan

34

Functions with no return values • But it only makes sense to do this if the function returns a value % We can't assign the result of a function to a % variable if that function doesn't return anything number = 4; result = print1toN(number);

ENGG1801 Engineering Computing Jason Chan

35

Example without Functions % This code prints the integers 1 to 3 % See lecture 5-2 for i = 1:3 disp(i); end

ENGG1801 Engineering Computing Jason Chan

36

Examples of Functions (2) % This function prints 1 to 3 using a for % loop. It takes no parameters, which % means it always does the same thing function print1to3() for i = 1:3 disp(i); end end

ENGG1801 Engineering Computing Jason Chan

37

Examples of Functions (3) % This function prints 1 to 100 using a % for loop function print1to100() for i = 1:100 disp(i); end end

ENGG1801 Engineering Computing Jason Chan

38

Examples of Functions (4) % This function prints all the integers % from 1 to the given value, assuming % n >= 1. It does different things % depending on what it has been given function print1toN(n) for i = 1:n disp(i); end end

ENGG1801 Engineering Computing Jason Chan

39

Examples of Functions (5) % This function prints all the integers % between the 2 given values, % assuming low = 85 grade = 'HD'; elseif mark >= 75 grade = 'D'; elseif mark >= 65 grade = 'CR'; elseif mark >= 50 grade = 'P'; else grade = 'F'; end end ENGG1801 Engineering Computing Jason Chan

49

Different return and parameter types % This function takes numeric parameter, % and returns a boolean / logical result % (true is returned if given number is 0, % otherwise false is returned) function result = isZero(n) if n == 0 result = true; else result = false; end end ENGG1801 Engineering Computing Jason Chan

50

Different data types in Matlab data type

Description

Examples

Numeric

Any kind of number: - Integer - Decimal number - Scientific notation

34 -63747 3.14159 6.022e23

String

Any series of characters on the keyboard

'abc' 'I love ENGG1801!' '34'

Logical*

Boolean values (true or false)

true false

* Logical values, when printed out, appear as 1 (for true) and 0 (for false), but that is just how they appear on screen. They are actually coded and stored as true and false values, not numeric values. ENGG1801 Engineering Computing Jason Chan

51

Parameter but no returned value % This function prints the integers from % 1 up to the given integer n, assuming % n >= 1. Nothing is returned function print1toN(n) for i = 1:n disp(i); end end

ENGG1801 Engineering Computing Jason Chan

52

Many parameters, 1 returned value % This function takes 2 numbers, and % returns just 1 number: the difference % between the 2 given numbers function difference = getDifference(a, b) % This difference could be negative difference = a – b; % Make sure difference is positive if difference < 0 difference = difference * -1; end end

ENGG1801 Engineering Computing Jason Chan

53

Returning values • When a function says it will return a value, you must make sure that it returns a value in all scenarios* • Consider this example again:

* The only exception to this rule will be covered in lecture 7-1, when we detect an error and use the error function ENGG1801 Engineering Computing Jason Chan

54

Returning values % This function takes a mark (numeric parameter) % and returns the grade (a string, or any series % of characters on the keyboard) function grade = convertMarkToGrade(mark) if mark >= 85 grade = 'HD'; elseif mark >= 75 grade = 'D'; elseif mark >= 65 grade = 'CR'; elseif mark >= 50 grade = 'P'; else grade = 'F'; end end ENGG1801 Engineering Computing Jason Chan

55

Returning values • What happens if we remove the else part of the if statement? • Our code will now look like this:

ENGG1801 Engineering Computing Jason Chan

56

Returning values function grade = convertMarkToGrade(mark) if mark >= 85 grade = 'HD'; elseif mark >= 75 grade = 'D'; elseif mark >= 65 grade = 'CR'; elseif mark >= 50 grade = 'P'; % else has been deliberately removed % This is bad, because the function says it % will return grade, but we didn't initialize % grade if the student failed end end

ENGG1801 Engineering Computing Jason Chan

57

Returning values • If mark < 50, the function does not initialize variable grade • Now, let’s try using our function like this: % Use the function, giving it a mark, % and print out the grade that the % function gives back to us mark = 47; grade = convertMarkToGrade(mark); disp(grade); ENGG1801 Engineering Computing Jason Chan

58

Returning values

• Matlab says that grade may not be assigned (given a value, see lecture 4-1, slide 38) ENGG1801 Engineering Computing Jason Chan

59

Returning values vs Printing • Almost always, it’s better to return a value instead of printing something to the screen – The calling code may be in the middle of printing something else, and doesn’t want to print out the result of this function (it just needs the result to do something) – If the function prints something, then the calling code can’t control how it is printed (e.g. in a sentence, formatted neatly, certain number of decimal places, etc). ENGG1801 Engineering Computing Jason Chan

60

Returning values vs Printing • Your function should not print anything unless there is a specific reason to do so: – The function specifically has to print, e.g. • Print a menu to screen • Exam Q tells you to print something

– The user of the program needs to see what the result is, and the output format is clear – You are trying to debug your program, and want to know what a variable’s value is at different points of the program ENGG1801 Engineering Computing Jason Chan

61

Returning values vs Printing • So, to summarize: Inside a function, do not print anything unless the Q asks you to do so • Otherwise, marks will be lost in the Lab Exams and Final Exam

ENGG1801 Engineering Computing Jason Chan

62

The return keyword • When Matlab reaches the return keyword, it gets out of the function immediately • This allows you to write simpler code – See example on next slide

ENGG1801 Engineering Computing Jason Chan

63

The return keyword % Returns the average value of all elements in the given % array; if array is empty, then 0 is returned function average = getAverage(numbers) % Get out of function straight away if array is empty if length(numbers) == 0 average = 0; return; end % The rest is the same as Lab 5, Exercise 4.1 total = 0; for n = numbers total = total + n; end average = total / length(numbers); end ENGG1801 Engineering Computing Jason Chan

64

Documentation • Purpose of functions (for a user): – The user of the function knows what the function does – But the user does not know how the function does it

• So the user of the function needs to know: – The function name – What parameters (if any) need to be given – What returned value (if any) will be given back ENGG1801 Engineering Computing Jason Chan

65

Documentation • This information can be given by the author of the function with documentation – Write comments written at the top of an .m file – These comments are visible to users of the function when they use the help command, followed by the function name – The comment should include the function header (function name, returned variable and parameters), and describe them if necessary ENGG1801 Engineering Computing Jason Chan

66

Documentation % Returns the average value of all elements in the % given array; if array is empty, then 0 is % returned % % average = getAverage(numbers) function average = getAverage(numbers) % Code left out to save space... end

ENGG1801 Engineering Computing Jason Chan

67

To Know • • • •

General vs specific cases Returning values from functions Parameters vs returning values Different data types (numbers, strings, booleans) • Returning values vs printing on screen, and why printing in functions is usually bad • The return keyword ENGG1801 Engineering Computing Jason Chan

68...


Similar Free PDFs