Download presentation

Presentation is loading. Please wait.

Published byKylan Beanland Modified over 2 years ago

1
MATLAB FUNDAMENTALS: USER DEFINED FUNCTIONS THE SYMBOLIC TOOLBOX HP 100 – MATLAB Wednesday, 10/29/2014 www.clarkson.edu/class/honorsmatlab

2
A Quote of the Week “Parties are good. But remember, eggs are cheap and Peploski’s house is closer.” -Dr. David Wick “I’m not sure if it’s the midpoint rule or the trapezoid rule but I’m pretty sure they are the same.” - Professor Thomas https://www.youtube.com/watch?v=zB92yoK242s

3
PSE # 2 Thoughts? Reaction? Questions? Comments?

4
What NOT to do to MATLAB

5
Continued….

6
User Defined Functions We will now discuss one of the last key fundamental ideas of programming in MATLAB.

7
What is a function? You already have seen them in action: – y = sin(x); – height = input('Enter Height: '); – x = pi.*r.^2 So, what is it then? – A function is simply a separate block of code that takes input(s) and then provides output(s).

8
Function: Visual

9
Why bother with functions? 1. It saves considerable computation time [For several technical reasons … ask a Comp Sci for more info] 2. It reduces bulky, repetitious code [Improves performance & reduces problems] (Read – Easier to Debug!!!) 3. You can re-use the functions over and over 4. It is what all the cool kids are doing.

10
How do they work in MATLAB? To create a user-defined function in MATLAB we must create “function m-files” – These “function m-files” can be accessed and used by MATLAB just like any of its built-in functions as long as the “function m-file” is in the current working directory or you tell MATLAB to look elsewhere.

11
Key Ideas: Remember functions simply: – Take input(s) and give output(s) – The calculations they perform are hidden from the user or calling code. To “call” a function simply means to use it.

12
Lingo Argument Input Argument What variables you are passing to the function as inputs. Output Argument The variables that are passed out of the function as outputs. Example: [numrow,numcol] = size(x)

13
Creating “Function m-files” Basic syntax: function [out1,out2,…] = function_name(in1,in2,…) % Enter a description here, it will be displayed if % the user types in “help function_name“ ... Do some calculations with: in1,in2... out1 = calculated results; out2 = calculated results; Now you must save the file: Save it with the SAME EXACT NAME as the name of your function. (MATLAB will suggest you do so, and yell at if you if don’t)

14
Syntax Decomposed function [out1,out2,…] = function_name(in1,in2,…) Output Argument(s) – as many as you like Function Declaration – Tell MATLAB this is a function! Input Argument(s) – as many as you like Function Name – Self Explanatory?

15
Syntax Decomposed function [out1,out2,…] = function_name(in1,in2,…) % Enter a description here, It will be displayed % If the user types in “help function_name” These comments tell people about the function. You should include things like: What does this function do? What are the Input Arguments? What are the Outputs? Anything Else that is important to know?

16
Example: celsius2kelvin Create a function that converts from Celsius to Kelvin. One Input Argument: Temperature in Celsius One Output Argument: Temperature in Kelvin Note: You should not display anything while running the function. You will use this function like so: >> tempinC = 0; >> tempinK = celsius2kelvin(tempinC); >> disp([ num2str(tempinC) 'Deg. C is '... num2str(tempinK) 'Kelvin‘]);

17
Example: function newtemp = celsius2kelvin(oldtemp) % Temperature conversion Program % Input: oldtemp -array or scalar % Output: newtemp-size(oldtemp) % Convert from C --> K newtemp = oldtemp + 273.15;

18
Argument Checking nargin('function_name') Determines the # of input arguments to the function given (function name given as a string) Useage: Inside of the function: tells how many input arguments there actually are. nargout('function_name') Same as above but determines # of output arguments

19
Variable Scope Local vs. Global variables: Local variables are defined ONLY inside of a particular function. So if you define a variable “x” inside of a function, and run the function from the command window, the variable x WILL NOT SHOW UP IN THE WORKSPACE Global variables are accessible by all functions since they will reside in the workspace. It is generally bad to use global variables, but they do have their uses

20
Global Variables To set a global variable we must initialize the variable as being “global” Syntax: global x y z x = 5; y = 6; z = 9; To use a global variable we must tell MATLAB it is a global variable: Syntax: global x Answer = x*5; Answer = [25]

21
More about Functions Many more advanced uses of functions are available: Anonymous functions Function functions Sub-functions Function handles “Toolboxes” of functions Persistent variables Private functions P-code files Inline functions Nested functions

22
Symbolic Mathematics Previous calculations in MATLAB relied on numerical or logical data The symbolic data type is another way to perform mathematical operations MATLAB utilizes the Maple 14 software Note: The symbolic toolbox is not included in all versions of MATLAB, it is included in the Educational Release.

23
Symbolic vs. Numeric In engineering, science, math and virtually all other fields it is always preferred to solve problem symbolically and THEN substitute in numbers. When working with computers, we had to do it backwards. Moving forward now

24
Symbolic in MATLAB What are they good for? Solving Equations*** Laplace Transforms Fourier Transforms Many other uses

25
Creating Symbolic Variables Syntax: sym('x','y','z') or syms x y z This creates x,y,z as symbolic variables

26
Symbolic Expressions Create: y=2*(x+3)^2/(x^2+6*x+9) – Syntax: Since x is already a variable: y = 2*(x+3)^2/(x^2+6*x+9); Create: PV = nRT(Ideal Gas Law) – Syntax: ideal_gas = sym(‘P*V=n*R*T’); Note: – “y” is a symbolic expression – “ideal_gas” is an equation

27
Manipulating Symbolics [num,den] = numden(y) Extracts the numerator and denominator from an expression expand(num) Expands the expression or equation: num = 2*(x+3)^2 2*x^2+12*x+18 factor(den) Factors the expression or equation: den = x^2+6*x+9 (x+3)^2

28
Manipulating Symbolics expand() factor() collect() simplify() simple() [num,den]=numden() --Not valid for equations See TABLE 11.1 in your Text (p. 384)

29
Solving Expressions & Equations The solve function: Determine the roots of equations Numerical answers for single variables Solve for unknown analytically Systems of equations, linear and non-linear Used with subs to find analytical solutions

30
Solve Syntax & Usage: E1 = sym('x-3') solve(E1) ans=3 solve('x^2-9') ans=[3;-3] Note: if x is already defined as a symbolic variable then the single quotes are not needed.

31
Solve Solving symbolic expressions in more than one variable: solve('a*x^2+b*x+c') ans = 1/2/a*(-b+(b^2-4*a*c)^(1/2)) 1/2/a*(-b-(b^2-4*a*c)^(1/2)) MATLAB will normally solve for ‘x’ in these cases, but you can specify which variable to solve for: solve('a*x^2+b*x+c', 'a') ans = -(b*x+c)/x^2

32
Solve Solve: – 5x 2 + 6x + 3 = 10 Try 1 st : Set expression equal to zero – 5x 2 + 6x – 7 = 0 solve(‘5*x^2+6*x-7’) Try 2 nd : If equation can’t be solved for 0 E2 = sym(‘5*x^2+6*x+3=10’) solve(E2) ans = -3/5 + 2/5*11^(1/2) -3/5 - 2/5*11^(1/2)

33
Solve: Notes Note: – The answers produced are still symbolic expressions! – Convert them to numbers: double(ans) Converts symbolic to double-precision floating point (that’s a number) – Maple is picky:Integers vs. Floating Point solve('5.0*x^2.0+6.0*x-7.0') ans =.72664991614245993964597309466828 -1.9266499161421599396459730946683

34
Solve: Systems System of Equations: one = sym('3*x + 2*y - z = 10'); two = sym('-x + 3*y + 2*z = 5'); three = sym('x - y - z = -1'); answer = solve(one,two,three) answer = x: [1x1 sym] y: [1x1 sym] z: [1x1 sym] What’s that??

35
Solve: Systems It is a data type we just learned about! Structures How do I get x,y,z then? answer.x -2 answer.y 5 answer.z -6 Or…

36
Solve: Systems Alternatively: [x y z] = solve(one,two,three) x = -2 y = 5 z = -6 Note: The results are returned alphabetically, regardless of what you call it in the output arguments!!!

37
Substitution We have a symbolic expression, now we want to substitute values into it. E4 = sym(‘a*x^2 + b*x +c’); subs(E4,’x’,’y’) ans = a*(y)^2+b*(y)+c We can also substitute in numbers! subs(E4,’x’,3) ans = 9*a+3*b+c Note: – You don’t need single quotes if the variable is already defined as a symbolic.

38
Substitution Substitute in an array of numbers: E6 = subs(E4,{‘a’,’b’,’c’},{1,2,3}) E6 = x^2+2*x+3 numbers = 1:5; subs(E6,’x’,numbers) ans = 611182738

39
Symbolic Plotting There exists many plotting functions that can be used with symbolic functions. See Table 11.3 on page 400 for more details. Basic form: ezplot() y = sym(‘x^2-2’); ezplot(y) Default x domain is -2pi : 2pi ezplot(y,[-15,15]) Plots y for a domain of -15 to 15

40
Symbolic Plotting Implicit functions: x^2 + y^2 = 1 All of these will work: ezplot(‘x^2 + y^2 =1’) ezplot(‘x^2 + y^2 – 1’) z = sym(‘x^2 + y^2 – 1’) ezplot(z)

41
Symbolic Plotting ezmesh(z) ezmeshc(z) ezsurf(z) ezsurfc(z) ezcontour(z) ezcontourf(z) ezpolar(r) ezplot3(x,y,z) Function Types: z(x) z(x,y) r(theta) x(t),y(t),z(t) Parametric Equations Three Dimensional Plotting

42
Symbolic Plotting Examples: syms t x = sin(t); y = cos(t); z = t; explot3(x,y,z,[0,20]);

43
Symbolic Plotting Examples: syms x y z = x*exp(-x^2-y^2); ezmesh(z,[-2.5,2.5]);

44
Symbolic Calculus Differentiation: diff(f) diff(f,’t’) diff(f,n) diff(f,’t’,n) f : --Symbolic expression ‘t’: --With respect to var t n : --Take the n th derivative

45
Symbolic Calculus Differentiation: – Example: y = sym(‘x^2 + t - 3*z^3’) diff(y) 2*x diff(y,’z’) -9*z^2 Note: – ‘x’ is the default value to differentiate with respect to

46
Symbolic Calculus Integration: – int(f) – int(f,’t’) – int(f,a,b) – int(f,’t’,a,b) f : --Symbolic Expression ‘t’: --With respect to var t a,b: --Upper & lower bounds for definite integral. May be numeric or symbolic

47
Symbolic Calculus Integration: – Example: y = sym(‘3*x^2 – 2*x + 1’) int(y) ans = x^3-x^2+x int(y,’a’,’b’) ans = b^3-a^3-b^2+a^2+b-a Note: – ‘x’ is the default value to differentiate with respect to. – No constant of integration for indefinite integrals!

48
Questions? Comments about Symbolics: – They are nice & nifty… – But they are slow. Homework: Read Chapters:6, 11 Problems:6.3, 11.15, 11.31 6.3 asks you to make a function. That MUST be its own.m file. Please put 11.15, 11.31 and the rest of 6.3 (the part where you use the function) in a second.m file. Make sure you submit the function.m file!!

Similar presentations

OK

CSE 123 Symbolic Processing. Declaring Symbolic Variables and Constants To enable symbolic processing, the variables and constants involved must first.

CSE 123 Symbolic Processing. Declaring Symbolic Variables and Constants To enable symbolic processing, the variables and constants involved must first.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google