HP 100 - MATLAB

advertisement
MATLAB FUNDAMENTALS:
USER DEFINED FUNCTIONS
THE SYMBOLIC TOOLBOX
HP 100 – MATLAB
Wednesday, 10/29/2014
www.clarkson.edu/class/honorsmatlab
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
PSE # 2




Thoughts?
Reaction?
Questions?
Comments?
What NOT to do to MATLAB
Continued….
User Defined Functions

We will now discuss one of the last key fundamental
ideas of programming in MATLAB.
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).
Function: Visual
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.
4.
You can re-use the functions over and over
It is what all the cool kids are doing.
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.
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.
Lingo

Argument
 Input
Argument
 What
 Output
 The
variables you are passing to the function as inputs.
Argument
variables that are passed out of the function as outputs.
 Example:
[numrow,numcol] = size(x)
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)
Syntax Decomposed
function [out1,out2,…] = function_name(in1,in2,…)
Function Name – Self Explanatory?
Output Argument(s) – as many as you like
Function Declaration – Tell MATLAB this is a function!
Input Argument(s) – as many as you like
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
 You
comments tell people about the function.
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?

Example: celsius2kelvin

Create a function that converts from Celsius to Kelvin.

One Input Argument:


One Output Argument:


Temperature in Celsius
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‘]);
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;
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
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
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]
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

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.
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 
Symbolic in MATLAB

What are they good for?
 Solving
Equations***
 Laplace Transforms
 Fourier Transforms
 Many other uses
Creating Symbolic Variables

Syntax:
sym('x','y','z')
or

syms x y z
This creates x,y,z as symbolic variables
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
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
Manipulating Symbolics
expand()
factor()
collect()
simplify()
simple()
[num,den]=numden()
--Not valid for equations
See TABLE 11.1 in your Text (p. 384)
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
Solve
Syntax & Usage:
E1 = sym('x-3')
solve(E1)
solve('x^2-9')


ans=3
ans=[3;-3]
Note: if x is already defined as a symbolic variable then the
single quotes are not needed.
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

Solve
•
Solve:
–
•
5x2 + 6x + 3 = 10
Try 1st : Set expression equal to zero
5x2 + 6x – 7 = 0
solve(‘5*x^2+6*x-7’)
–
•
Try 2nd : 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)
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
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]
 What’s that??
z: [1x1 sym]
Solve: Systems

It is a data type we just learned about!
 Structures

How do I get x,y,z then?
answer.x
answer.y
answer.z

Or…



-2
5
-6
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!!!
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.
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 =
6
11
18
27
38
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
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)
Symbolic Plotting
• Three Dimensional 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)
 z(x,y)
 z(x,y)
 z(x,y)
 z(x,y)
 r(theta)
 x(t),y(t),z(t)
Parametric Equations
Symbolic Plotting
Examples:
x = sin(t), y = cos(t), z = t
syms t
x = sin(t);
y = cos(t);
z = t;
explot3(x,y,z,[0,20]);
20
15
z

10
5
0
1
0.5
1
0.5
0
0
-0.5
y
-0.5
-1
-1
x
Symbolic Plotting

Examples:
syms x y
z = x*exp(-x^2-y^2);
ezmesh(z,[-2.5,2.5]);
2
2
x exp(-x -y )
0.5
0
-0.5
2
1
2
1
0
0
-1
-2
y
-1
-2
x
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 nth derivative
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
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
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!
Questions?
•
Comments about Symbolics:
–
–
•
They are nice & nifty…
But they are slow.
Homework:
 Read
Chapters:
 Problems:

6, 11
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!!
Download