Download MATLAB Functions: Understanding Inputs, Outputs, and User-Defined Functions - Prof. Maria and more Study notes Engineering in PDF only on Docsity! 4/13/2009 1 ENGR 1731 Computing for Engineers Georgia Southern University Mechanical and Electrical Engineering Technology Spring 2009 Prof. Alba‐Flores ‐ Functions MATLAB Functions • A function is a program that can be called i id thns e ano er program. • MATLAB has many built in functions that can be called to calculate arithmetic, logarithmic, trigonometric and special functions. • A list of functions available in MATLAB is given next 4/13/2009 2 Common Matlab Built in Functions sqrt(x) – Square root function exp(x) – Exponential function log(x) – Natural Logarithm log10(x) – Common logarithm cos(x) – Cosine function sin(x) – Sine function tan(x) – Tangent function ( ) facos x – Inverse cosine unction asin(x) – Inverse sine function atan(x) – Inverse tangent function Function Calling • In order to execute a function we just put the name of the function and assign its result to a variable: y = tan(x); z = cos(x) – sin(x); Function calls 4/13/2009 5 User Defined Functions (cont.) • Function Definition Syntax function [Output Variable List] = function name (Input Variable list) end Description function [out1, out2, ...] = funname (in1, in2, ...) defines function funname that accepts inputs in1, in2, etc. and returns outputs out1, out2, etc. All functions should end with the instruction end You add new functions to the MATLAB vocabulary by expressing them in terms of existing functions. The existing commands and functions that compose the new function reside in a text file ( M‐file) funname.m Function Definition Example 1 function factorial = fac(n) f t i l 1ac or a = ; for i = 1 : n factorial = factorial * i; end end Function name: fac Output variable: factorial Input variable: n 4/13/2009 6 Function Documentation % This function can be used to calculate the factorial % of an integer, the input variable is the number to % calculate the factorial the output variable is the % factorial of the received number function factorial = fac(n) factorial =1 ; for i = 1 : n *factorial = factorial i ; end end Function Definition Example 2 function sum = suma(num1, num2, num3) 1 2 3sum = num + num + num ; end Function name: suma O t t i blu pu var a e: sum Input variables: num1, num2, num3 4/13/2009 7 Function Definition Example 3 We can create a Matlab file called stat.m that defines a new function called stat that calculates the mean and t d d d i ti f ts an ar ev a on o a vec or. function [mean, stdev] = stat(x) n = length(x); mean = sum(x)/n; stdev = sqrt(sum(( x – mean).^2/n)); end Function name: stat Output variables: mean, stdev Input variable: x