A blog to help electrical engineers and students to learn electrical engineering topics. Basic Electrical Engineering, Power Systems, Electrical Machines, tec.. Now special course on MATLAB for Beginners.

Class

Class

Wednesday, January 4, 2017

Anonymous and Inline Functions in MATLAB

Anonymous Functions

MATLAB's anonymous functions provide an easy way to specify a function. An anonymous function is a function defined without using a separate function file. It is a MATLAB feature that lets you define a mathematical expression of one or more inputs and either assign that expression to a function. This method is good for relatively simple functions that will not be used that often and that can be written in a single expression.
An anonymous function of any number of variables can be created by giving the @ symbol, followed by a variable list, followed by the MATLAB expression. Anonymous function can be written in Command Window, script file, or inside user-defined function. Anonymous functions can only have one expression and can only return a single variable.

To give the anonymous function a name, simply put the function's name on the left side of an equal sign and the anonymous function on the right. 
                     NAME = @(ARGLIST)EXPRESSION 
  • NAME is name of the function. (using rules for names of user-defined functions) 
  • @ - a function handle, an object that has information about the function 
  • ARGLIST is the input arguments (a comma-separated list). 
  • The body of the function, to the right of the parentheses, is a single line MATLAB expression.

Inline Functions

The inline command lets you create a function of any number of variables by giving a string containing the function followed by a series of strings denoting the order of the input variables. This method is good for relatively simple functions that can be written in a single expression. It is similar to an Anonymous Function. Inline functions cannot access variables in the work space, even if those variables are global – this is the main difference with the anonymous functions.
The expression to be evaluated is defined in single quotes, followed in order by the variables of the function also surrounded by single quotes. 
                       Name = inline(‘expression', 'arg1', ‘arg2')


submit to reddit