250 likes | 400 Views
Functions in Matlab. Builtin and user defined functions. Builtin Functions. Exponential exp(x) sqrt(x) Logarithmic log(x) natural logarithm ln log10(x) log2(x). Builtin continued. numeric ceil(x) round to nearest integer towards +
E N D
Functions in Matlab Builtin and user defined functions
Builtin Functions • Exponential • exp(x) • sqrt(x) • Logarithmic • log(x) natural logarithm ln • log10(x) • log2(x)
Builtin continued • numeric • ceil(x) round to nearest integer towards + • fix(x) round to nearest integer towards 0 • floor(x) round to nearest integer towards - • round(x) round to nearest integer • sign(x) +1, 0 or -1 • rem(x,y) Finds remainder of x/y • complex • abs(x) absolute value • angle(x) in complex plane • conj(x) • imag(x) • real(x)
Builtin continued • Trigonometric and their inverse • cos(x) acos(x) • sin(x) asin(x) • tan(x) atan(x) • cot(x) acot(x) • csc(x) acsc(x) • sec(x) asec(x) • atan2(x,y)
Builtin Functions continued • Hyperbolic and their inverse • cosh(x) acosh(x) • coth(x) acoth(x) • csch(x) acsch(x) • sech(x) asech(x) • sinh(x) asinh(x) • tanh(x) atanh(x)
Remarks • All trigonometric functions require the use of radians and not degrees • All buitlin functions can also be used with complex numbers. • To understand the meaning with complex numbers need to go back to basic definitions: • exp(i x) = cos(x) + i sin(x) • sin(x) =(exp(i x) - exp(-i x) )/(2 i) • sinh(x) = (exp(x) – exp(-x) )/2 • Basic example • exp( a + i b) = exp(a) exp(i b) = exp(a) (cos(x) + i sin(x))
Remarks continued • Since a trigonometric function is periodic each value has many inverse values • Matlab will return only one value, the so called 'principle value' • For engineering applications it is important to check that this is the correct value. • Plotting a complex valued function z =f(x+iy) is not possible. It requires a four dimensional space (x,y,u,v) since z = u+iv
Builtin Functions for vectors • max(x) • returns largest value in vector x • [a,b] = max(x) • returns largest value in a and index where found in b • max(x,y) • x and y arrays of same size, returns vector of same length with lager value from corresponding positions in x and y • same type of functions are available for min
Builtin functions for vectors • sort(x) • mean(x) • median(x) • sum(x) • prod(x) • cumsum(x) • returns vector of same size with cummulative sum of x i.e. x=[4,2,3] returns [4,5,9] • cumprod(x) • returns cummulative products in vector of same size
Builtin functions applied to matrices • Matrices (arrays) are stored in column major form • When builtin functions for vectors are applied to a matrix function operates on columns and returns a row vector
User defined functions • Similar to script files except that • temporary variables remain local • function use standardized input and output parameters • Script files good for quick and dirty jobs • Functions can be used over and over again with no side effects • Similar to subroutine, function or procedure in other programming languages like Fortran, PL/I, Pascal, C, C++
Example • f(x,y) = 3*x +6*y^2 • Questions to be answered first: Are x and y allowed to be arrays? • Since Matlab treats everything as an array it is best to allow all parameters to be an array • If x and y are arrays they have to be of the same size and f(x,y) is returned as an array of the same size • In above example x or y could be scalar (i.e. a constant) and function still makes sense
Matlab code placed in file fun.m • function z = fun(x,y) • u=3*x; • z = u + 6*y.^2 ; • Note operator .^ to allow for an array • Here the operator * does not require the array operator .* since it is a multiplication with a constant • + alays operates on the elements of an array thus .+ is not defined • u is a local variable in will not be available after the function is executed • u is used in the example for demonstration only. It would be better to write z = 3*x+6*y.^2;
Remarks • Check that function name fun does not yet exist via: exist fun • The input parameters x, y and the output parameter z are local • fun(3,4) does not create a variable z instead it returns the value in ans • q = fun(x0,y0) gives anwser to q, assuming x0 and y0 are defined • fun([2:5],[7:10]) works since arrays are of the same length
Parameters for functions • Input parameters: 0 or more • parameter list enclosed by ( ) • if there are no parameters can omit () • function show_date • today = date • Example with three input parameters • function volume = box(height, width, depth) • volume = height.*width.*depth;
Parameters for user defined functions • Output parameter 0 or more • parameter list enclosed by [ ] • 0 or 1 output parameter, can omit [ ] • 2 or more parameters separated by commas • first output parameter ist set to ans, if function is called without output parameters • Examples: • function [areaC, cirumC] = circle(radius); • function areaSquare = square(sides) ;
Remarks • Why pass constants like g Earth's gravitation to a function? • g varies with units and forces user to select the proper unit • a better choice is to let the user select at the very beginning, which units are to be used • in this case need to state in function • global g • and in main progra • global g • g = 9.81 • Input parameters are local • even if they are change in the function the original value remains unchanged • if the value in the calling program needs to be changed have to return value as an output parameter
Function handle • Useful as parameter to other functions • Can be considered as an alternate name for a function – but with more capabilities • Example: • sine_handle = @sin • sine_handle(x) same values as sin(x) for all x • x = [0 : 0.01 : 2*pi] ; • y = sin( x ); • plot(x,y) • plot( x, sin(x) ) • plot( [0 : 0.01 : 2*pi] , sin( [0 : 0.01 : 2*pi] )) ;
Function handle continued • In last example everything is on one line • It requires writing the interval twice • It would be more convient to write • gen_plot( function_handle, interval ) • The first parameter has to be a function handle and not just the name of a function • gen_plot( sin, [0 : 0.01 : 2*pi ] ) does not make sense to Matlab, but the following does • gen_plot( sine_handle, [0 : 0.01 : 2*pi] )
Using a function handle • function [] = gen_plot( func_handle, interval ) ; • plot( interval, func_handle(interval) ) ; • When plotting lots of functions it may be useful to have gen_plot available • The example shows how to pass functions as parameters. • Another use is anonymous functions • Assume the user needs to work temporaily with the function x3+3*x – 1 • Instead of writing the function • function y = mypoly(x) ; • y = x.^3+3*x-1 • and storing it as mypoly.m in subdirectory work we can use an anonymous function with the function handle mypoly • mypoly = @(x) x.^3+3*x-1
Using anonymous functions • With a function handle an anonymous function can be used like any other • gen_plot( mypoly, [-10 : 0.01 : 10] ) • fzero( mypoly, 0.0 ) • roots( [1, 0, 3, -1] ) • Without the function handle the anonymous function can be inserted directly as the parameter • gen_plot( @(x) x.^3+3*x-1, [-10 : 0.01 : 10] )
More examples • f1 = @(x) x + 2* exp(-x) -3 • fzero( f1, 0 ) • fzero( f1, 1 ) • Assume f1 had been defined as a function and kept in f1.m then • fzero( f1, 0 ) would be in error • Besides function handle Matlab provides the the following alternate method • fzero( 'f1', 0 ) • fzero( 'sin', 0 ) • fzero( 'x.^3', 0 ) need to use default variable name