function Handles

Function Handles

A function handle is a MATLAB value that provides a means of calling a function indirectly. You can pass function handles in calls to other functions (often called function functions). You can also store function handles in data structures for later use (for example, as Handle Graphics callbacks).

Constructing a Function Handle

Use the following syntax to construct a function handle, preceding the name of the function with an @ sign. Use only the function name, with no path information, after the @ sign:

  • fhandle = @functionname

MATLAB maps the handle to the function you specify and saves this mapping information in the handle. If there is more than one function with this name, MATLAB maps to the one function source it would dispatch to if you were actually calling the function.

A function handle retains that same mapping even if its corresponding function goes out of scope. For example, if, after creating the handle, you change the MATLAB path so that a different function of the same name now takes precedence, invoking the function handle still executes the code to which the handle was originally mapped.

Handles to Anonymous Functions

Another way to construct a function handle is to create an anonymous function. For example,

  • sqr = @(x) x.^2;

creates an anonymous function that computes the square of its input argument x. The variable sqr contains a handle to the anonymous function. See Anonymous Functions for more information.

Arrays of Function Handles

To store function handles in an array, use a cell array:

  • trigFun = {@sin, @cos, @tan};



Invalid or Obsolete Function Handles

If you create a handle to a function that is not on the MATLAB path, or if you load a handle to a function that is no longer on the path, MATLAB catches the error only when the handle is invoked. You can assign an invalid handle and use it in such operations as func2str. MATLAB catches and reports an error only when you attempt to use it in a runtime operation.

Calling a Function Using Its Handle

To execute a function associated with a function handle, use the syntax shown here, treating the function handle fhandle as if it were a function name:

  • fhandle(arg1, arg2, ..., argn)

If the function being called takes no input arguments, then use empty parentheses after the function handle name:

  • fhandle()

Simple Function Handle Example

The following example calls a function plotFHandle, passing it a handle for the MATLAB sin function. plotFHandle then calls the plot function, passing it some data and the function handle to sin. The plot function calls the function associated with the handle to compute its y-axis values:

  • function x = plotFHandle(fhandle, data)
    plot(data, fhandle(data))

Call plotFhandle with a handle to the sin function and the value shown below:

  • plotFHandle(@sin, -pi:0.01:pi)

Functions That Operate on Function Handles

MATLAB provides the following functions for working with function handles. See the reference pages for these functions for more information.

Function Description
functions Return information describing a function handle.
func2str Construct a function name string from a function handle.
str2func Construct a function handle from a function name string.
save Save a function handle from the current workspace to a MAT-file.
load Load a function handle from a MAT-file into the current workspace.
isa Determine if a variable contains a function handle.
isequal Determine if two function handles are handles to the same function.
Posted in Matlab | Leave a comment

COmparing Handle and Value Classes

Comparing Handle and Value Classes

Why Select Handle or Value

MATLAB support two kinds of classes — handle classes and value classes. The kind of class you use depends on the desired behavior of the class instances and what features you want to use.

Use a handle class when you want to create a reference to the data contained in an object of the class, and do not want copies of the object to make copies of the object data. For example, use a handle class to implement an object that contains information for a phone book entry. Multiple application programs can access a particular phone book entry, but there can be only one set of underlying data.

The reference behavior of handles enables these classes to support features like events, listeners, and dynamic properties.

Use value classes to represent entities that do not need to be unique, like numeric values. For example, use a value class to implement a polynomial data type. You can copy a polynomial object and then modify its coefficients to make a different polynomial without affecting the original polynomial.

Which Kind of Class to Use describes how to select the kind of class to use for your application.

Passing Objects to Functions compares handle and value object behavior when used as arguments to functions.

Behavior of MATLAB Built-In Classes

If you create an object of the class int32 and make a copy of this object, the result is two independent objects having no data shared between them. The following code example creates an object of class int32 and assigns it to variable a, and then copies it to b. When you raise a to the fourth power and assign the value again to the variable a, MATLAB creates an object with the new data and assigns it to the variable a, overwriting the previous assignment. The value of b does not change.

a = int32(7);
b = a;
a = a^4;

MATLAB copies the value of a to b, which results in two independent versions of the original object. This behavior is typical of MATLAB numeric classes.

Handle Graphics classes return a handle to the object created. A handle is a variable that references an instance of a class. If you copy the handle, you have another variable that refers to the same object. There is still only one version of the object data. For example, if you create a Handle Graphics line object and copy its handle to another variable, you can set the properties of the same line using either copy of the handle.

x = 1:10; y = sin(x);
h1 = line(x,y);
h2 = h1;

>>set(h2,'Color','red') % line is red
>>set(h1,'Color','green') % line is green
??? Error using ==> set
Invalid handle object.

Note also, if you delete one handle, all copies are now invalid because you have deleted the single object that all copies point to.

// //

Behavior of User-Defined Classes

Value class instances behave like built-in numeric classes and handle class instances behave like Handle Graphics objects, as illustrated in Behavior of MATLAB Built-In Classes.

Value Classes

MATLAB associates objects of value classes with the variables to which you assign them. When you copy a value object, MATLAB also copies the data contained by the object. The new object is independent of changes to the original object. Instances behave like standard MATLAB numeric and struct classes. Each property behaves essentially like a MATLAB array See Memory Allocation for Arrays for more information.

Value Class Behavior

Use value classes when assigning an object to a variable and passing an object to a function must make a copy of the function. Value objects are always associated with one workspace or temporary variable and go out of scope when that variable goes out of scope or is cleared. There are no references to value objects, only copies which are themselves objects.

For example, suppose you define a polynomial class whose Coefficients property stores the coefficients of the polynomial. Note how copies of these value-class objects are independent of each other:

p = polynomial([1 0 -2 -5]);
p2 = p;
p.Coefficients = [2 3 -1 -2 -3];
ans =
   1 0 -2 -5

Creating a Value Class

All classes that are not subclasses of the handle class are value classes. Therefore, the following classdef creates a value class named myValueClass:

classdef myValueClass

Handle Classes

Objects of handle classes use a handle to reference objects of the class. A handle is a variable that identifies an instance of a class. When you copy a handle object, MATLAB copies the handle, but not the data stored in the object properties. The copy refers to the same data as the original handle. If you change a property value on the original object, the copied object reflects the same change.

All handle classes are subclasses of the abstract handle class. In addition to providing handle copy semantics, deriving from the handle class enables your class to:

Creating a Handle Class

Subclass the handle class explicitly to create a handle class:

classdef myClass < handle

See The Handle Superclass for more information on the handle class and its methods.

Subclasses of Handle Classes

If you subclass a class that is itself a subclass of the handle class, your subclass is also a handle class. You do not need to specify the handle superclass explicitly in your class definition. For example, the employee class is a subclass of the handle class:

classdef employee < handle

Create a subclass of the employee class for engineer employees, which is also a handle class. You do not need to specify handle as a superclass in the classdef:

classdef engineer < employee

Handle Class Behavior

A handle is an object that references its data indirectly. When constructing a handle, the MATLAB runtime creates an object with storage for property values and the constructor function returns a handle to this object. When you assign the handle to a variable or when you pass the handle to a function, MATLAB copies the handle, but not the underlying data.

For example, suppose you have defined a handle class that stores data about company employees, such as the department in which they work:

classdef employee < handle
      Name = ''
      Department = '';
      function e = employee(name,dept)
         e.Name = name;
         e.Department = dept;
      end % employee
      function transfer(obj,newDepartment)
         obj.Department = newDepartment;
      end % transfer

The transfer method in the previous code changes the employee’s department (the Department property of an employee object). In the following statements, e2 is a copy of the handle object e. Notice that when you change the Department property of object e, the property value also changes in object e2.

e = employee('Fred Smith','QE');
e2 = e; % Copy handle object
ans =

The variable e2 is an alias for e and refers to the same property data storage as e.

Initializing Properties to Handle Objects

See How to Initialize Property Values for information on the differences between initializing properties to default values in the properties block and initializing properties from within the constructor. Also, see Arrays of Handle Objects for related information on working with handle classes.

employee as a Value Class

If the employee class was a value class, then the transfer method would modify only its local copy of the employee object. In value classes, methods like transfer that modify the object must return a modified object to copy over the existing object variable:

function obj = transfer(obj,newDepartment)
   obj.Department = newDepartment;

When you call transfer, assign the output argument to create the modified object.

e = transfer(e,'Engineering');

In a value class, the transfer method does not affect the variable e2, which is a different employee object. In this example, having two independent copies of objects representing the same employee is not a good design. Hence, implement the employee class as a handle class.

Deleting Handles

You can destroy handle objects before they become unreachable by explicitly calling the delete function. Deleting the handle of a handle class object makes all handles invalid. For example:

??? Invalid or deleted object.

Calling the delete function on a handle object invokes the destructor function or functions for that object. See Handle Class Delete Methods for more information.

Posted in Matlab | Leave a comment

Overloaded MATLAB Functions

Overloaded MATLAB Functions

An overloaded function is an additional implementation of an existing function that has been designed specifically to handle a certain data type. When you pass an argument of this type in a call to the function, MATLAB looks for the function implementation that handles that type and executes that function code.

Each overloaded MATLAB function has an M-file on the MATLAB path. The M-files for a certain data type (or class) are placed in a directory named with an @ sign followed by the class name. For example, to overload the MATLAB plot function to plot expressions of a class named polynom differently than other data types, you would create a directory called @polynom and store your own version of plot.m in that directory.

You can add your own overloads to any function by creating a class directory for the data type you wish to support for that function, and creating an M-file that handles that type in a manner different from the default. See Setting Up Class Directories and Designing User Classes in MATLAB.

When you use the which command with the -all option, MATLAB returns all occurrences of the file you are looking for. This is an easy way to find functions that are overloaded:

  • which -all set          % Show all implementations for 'set'

Posted in Uncategorized | Leave a comment

M file programming III Subfunctions

1. Subfunctions

Function M-files can contain code for more than one function. The first function in the file is the primary function, the function invoked with the M-file name.Additional functions within the file are subfunctions that are only visible to the primary function or other subfunctions in the same file.

Each subfunction begins with its own function definition line. The functions immediately follow each other. The various subfunctions can occur in any order, as long as the primary function appears first.

function [avg,med] = newstats(u) % Primary function

% NEWSTATS Find mean and median with internal functions.

n = length(u);

avg = mean(u,n);

med = median(u,n);

function a = mean(v,n) % Subfunction

% Calculate average.

a = sum(v)/n;

function m = median(v,n) % Subfunction

% Calculate median.

w = sort(v);

if rem(n,2) == 1

m = w((n+1)/2);


m = (w(n/2)+w(n/2+1))/2;


The subfunctions mean and median calculate the average and median of the input list. The primary function newstats determines the length of the list and calls the subfunctions, passing to them the list length n. Functions within the same M-file cannot access the same variables unless you declare them as global within the pertinent functions, or pass them as arguments. In addition, the help facility can only access the primary function in an M-file.

When you call a function from within an M-file, MATLAB first checks the file to see if the function is a subfunction. It then checks for a private function (described in the following section) with that name, and then for a standard M-file on your search path. Because it checks for a subfunction first, you can supersede existing M-files using subfunctions with the same name, for example, mean in the above code. Function names must be unique within an M-file, however



2. Private Functions

Private functions are functions that reside in subdirectories with the special name private.  They are visible only to functions in the parent directory. For example, assume the directory newmath is on the MATLAB search path. A subdirectory of newmath called private can contain functions that only the functions in newmath can call.


3. Variables



Local Variables  

Each MATLAB function has its own local variables. These are separate from those of other functions, and from those of the base workspace. Variables defined in a function do not remain in memory from one function call to the

next, unless they are defined as global or persistent.

Scripts, on the other hand, do not have a separate workspace. They store their variables in a workspace that is shared with the caller of the script. When called from the command line, they share the base workspace. When called from a function, they share that function’s workspace.

Note If you run a script that alters a variable that already exists in the caller’s workspace, that variable is overwritten by the script.


Global Variables

If several functions, and possibly the base workspace, all declare a particular name as global, then they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the other functions declaring it global.


whos global — To see only those variables you have declared as global


Suggestions(RISKS) for Using Global Variables

You might, for example, unknowingly give a global variable in one function a name that is already used for a global variable in another function. When you run your application, one function may unintentionally overwrite the variable used by the other. This can be a difficult error to track down.

Another problem comes when you want to change the variable name. To make a change without introducing an error into the application, you must find every occurrence of that name in your codes

8. Alternatives to Using Global Variables.

Instead of using a global variable, you may be able to 

—> Pass the variable to other functions as an additional argument. In this way, you make sure that any shared access to the variable is intentional. If this means that you have to pass a number of additional variables, you can put them into a structure or cell array and just pass it as one additional argument.

—> Use a persistent variable, if you only need to make the variable persist in memory from one function call to the next.

9. Persistent Variables

Characteristics of persistent variables are

• You can only use them in functions.

• Other functions are not allowed access to them.

• MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next.

• If you clear the function or edit the M-file for that function, then MATLAB clears all persistent variables used in that function.

You must declare persistent variables as persistent before you can use them in a function. It is usually best to put persistent declarations toward the beginning of the function.

You would declare persistent variable SUM_X as follows:

persistent SUM_X

You can use the mlock function to keep an M-file from being cleared from memory, thus keeping persistent variables in the M-file from being cleared as well.



Data Types  

There are 15 fundamental data types (or classes) in MATLAB. Each of these data types is in the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional array of any size. Two-dimensional versions  of these arrays are called matrices.  

All of the fundamental data types are shown in lowercase text in the diagram below. Additional data types are user-defined, object-oriented user classes (structure), and java classes, that you can use with subclass of interface to Java.  

Matrices of type matrices having a small number of nonzero elements, a sparse matrix requires a fraction of the storage space required for an equivalent full matrix. Sparse matrices invoke special methods especially tailored to solve sparse problems.  

The the MATLAB double and logical may be either full or sparse. Forlogical  

11. Operator Overloading. You can overload the &, |, and ~ operators to make their behavior dependent upon the data type on which they are being used. Each of these operators has a representative function that is called whenever that operator is used. These are shown in the table below.


                                                                           Logical Operation                                                               Equivalent Function

                                                                                A & B                                                                                             and(A,B)

                                                                                A | B                                                                                               or(A,B)

                                                                                ~A                                                                                                    not(A)


12. Other Array Functions. Two other MATLAB functions that operate logically on arrays, but not in an element-wise fashion, are any and all. These functions  

show whether any or all elements of a vector, or a vector within a matrix or an array, are nonzero.  

The examples shown in the following table use array input A, where  

                             A = [0 1 2;  

                                    0 -3 8;  

                                     0 5 0];  

Function                                                                       Description                                                                                       Example  


any(A)                                         Returns 1 for a vector where any element       

                                                        of   the vector is  true (nonzero),  

                                                     and 0 if no elements are  true.any(A)  

ans =  

0 1 1  


the vector are  

elements are not  

Returns 1 for a vector where all elements oftrue (nonzero), and 0 if alltrue.all(A)  

ans =  

0 1 0  




























































13. if Statements and Empty Arrays  


That is,  

if A  





executes statement  

S0 when A is an empty array.  
































Posted in Matlab | Leave a comment

Programming M files II

1.  How Functions Work 

    You can call function M-files from either the MATLAB command line or from within other M-files. Be sure to include all necessary arguments, enclosing input arguments in parentheses and output arguments in square brackets. 




2.   Function Name Resolution 

When MATLAB comes upon a new name, it resolves it into a specific function by following these steps: 

                                                                   1 Checks to see if the name is a variable. 

                                                                   2 Checks to see if the name is a subfunction, a MATLAB function that resides in the same M-file as the calling function.   

                                                                   3 Checks to see if the name is a private function, a MATLAB function that resides in a private directory accessible only to M-files in the directory immediately above it.  

                                                                   4  Checks to see if the name is a function on the MATLAB search path. 

If you duplicate function names, MATLAB uses the first file it encounters with the specified name. 

If you duplicate function names, MATLAB executes the one found first using the above rules. It is also possible to overload functions. 


3. What Happens When You Call a Function 

When you call a function M-file from either the command line or from within another M-file, MATLAB parses the function into pseudocode and stores it in 

memory. This prevents MATLAB from having to reparse a function each time you call it during a session. The pseudocode remains in memory until you clear 

it using the clear function, or until you quit MATLAB. 

You can use clear in any of the following ways to remove functions from the MATLAB workspace. 


                              Syntax                                                                                                                    Description 

                         clear functionname                                                                                Remove specified function from workspace 

                        clear functions                                                                                          Remove all compiled M-functions 

                        clear all                                                                                                      Remove all variables and functions 


4.Creating P-Code Files 


You can save a preparsed version of a function or script, called P-code files, for later MATLAB sessions using the pcode function. For example, 

pcode average 

parses average.m and saves the resulting pseudocode to the file named average.p. This saves MATLAB from reparsing average.m the first time you call it in each session. 

MATLAB is very fast at parsing so the pcode function rarely makes much of a speed difference. 

One situation where pcode does provide a speed benefit is for large GUI applications. In this case, many M-files must be parsed before the application becomes visible. 

Another situation for pcode is when, for proprietary reasons, you want to hide algorithms you have created in your M-file. 


5. How MATLAB Passes Function Arguments 

From the programmer’s perspective, MATLAB appears to pass all function arguments by value. Actually, however, MATLAB passes by value only those arguments that a function modifies. If a function does not alter an argument but simply uses it in a computation, MATLAB passes the argument by reference to optimize memory use. 

6. Function Workspaces 

Each M-file function has an area of memory, separate from the MATLAB base workspace, in which it operates. This area is called the function workspace, with each function having its own workspace context. 

While using MATLAB, the only variables you can access are those in the calling context, be it the base workspace or that of another function. The variables that you pass to a function must be in the calling context, and the function returns its output arguments to the calling workspace context. You can however, define variables as global variables explicitly, allowing more than one workspace context to access them. 

7. Checking the Number of Function Arguments 

The nargin and nargout functions let you determine how many input and output arguments a function is called with. You can then use conditional statements to perform different tasks depending on the number of arguments. 


For example, 

function c = testarg1(a,b) 

if (nargin == 1) 

c = a.^2; 

elseif (nargin == 2) 

c = a + b; 


Given a single input argument, this function squares the input value. Given two inputs, it adds them together. 


Heres a more advanced example that finds the first token in a character string. 

A token is a set of characters delimited by whitespace or some other character. 

Given one input, the function assumes a default delimiter of whitespace; giventwo, it lets you specify another delimiter if desired. It also allows for two possible output argument lists. 

function [token,remainder] = strtok(string,delimiters) 

% Function requires at least one input argument 

if nargin < 1 

error(‘Not enough input arguments.’); 


token = []; remainder = []; 

len = length(string); 

if len == 0 



% If one input, use white space delimiter 

if (nargin == 1) 

delimiters = [9:13 32]; % White space characters 


i = 1; 

% Determine where non-delimiter characters begin 

while (any(string(i) == delimiters)) 

i = i + 1; 

if (i > len), return, end 


% Find where token ends 

start = i; 

while (~any(string(i) == delimiters)) 

i = i + 1; 

if (i > len), break, end 


finish = i – 1; 

token = string(start:finish); 

% For two output arguments, count characters after 

% first delimiter (remainder) 

if (nargout == 2) 

remainder = string(finish + 1:end); 



strtok function is a MATLAB M-file in the strfun directory 

Note The order in which output arguments appear in the function declaration line is important. The argument that the function returns in most cases appears first in the list. Additional, optional arguments are appended to 

the list. 

8. Passing Variable Numbers of Arguments 

The varargin and varargout functions let you pass any number of inputs or return any number of outputs to a function. 

MATLAB packs all specified input arguments into a cell array, a special kind of MATLAB array that consists of cells instead of array elements. Each cell can hold any size or kind of data one might hold a vector of numeric data, another in the same array might hold an array of string data, and so on. For output arguments, your function code must pack them into a cell array so that MATLAB can return the arguments to the caller. 

Heres an example function that accepts any number of two-element vectors and draws a line to connect them. 

function testvar(varargin) 

for k = 1:length(varargin) 

x(k) = varargin{k}(1); % Cell array indexing 

y(k) = varargin{k}(2); 


xmin = min(0,min(x)); 

ymin = min(0,min(y)); 

axis([xmin fix(max(x))+3 ymin fix(max(y))+3]) 


Coded this way, the testvar function works with various input lists; for example, 

testvar([2 3],[1 5],[4 8],[6 5],[4 2],[2 3]) 

testvar([-1 0],[3 -5],[4 2],[1 1]) 


Unpacking varargin Contents 

Because varargin contains all the input arguments in a cell array, its necessary to use cell array indexing to extract the data. For example, 


y(i) = varargin{i}(2); 

Cell array indexing has two subscript components: 


             —> The cell indexing expression, in curly braces 

            —> The contents indexing expression(s), in parentheses 

In the code above, the indexing expression {i} accesses the ith cell of varargin. The expression (2) represents the second element of the cell contents. 


Packing varargout Contents 

When allowing any number of output arguments, you must pack all of the output into the varargout cell array. Use nargout to determine how many output arguments the function is called with. For example, this code accepts a 

two-column input array, where the first column represents a set of x coordinates and the second represents y coordinates. It breaks the array into separate [xi yi] vectors that you can pass into the testvar function on the 

previous page. 

function [varargout] = testvar2(arrayin) 

for k = 1:nargout 

varargout{k} = arrayin(k,:) % Cell array assignment 


The assignment statement inside the for loop uses cell array assignment syntax. The left side of the statement, the cell array, is indexed using curly braces to indicate that the data goes inside a cell. 

Heres how to call testvar2

a = {1 2;3 4;5 6;7 8;9 0}; 

[p1,p2,p3,p4,p5] = testvar2(a); 


varargin and varargout in Argument Lists 

varargin or varargout must appear last in the argument list, following an required input or output variables. That is, the function call must specify the required arguments first. For example, these function declaration lines show the correct placement of varargin and varargout. 

function [out1,out2] = example1(a,b,varargin) 

function [i,j,varargout] = example2(x1,y1,x2,y2,flag) 






Posted in Matlab | Leave a comment

M file programming

1. Matlab enables you to write a series of commands in a file and the execute them with a single command. We can wirte our own matlab statements / program in an ordinary file, and give the file tthe name filename.m, the name of the file filename becomes the command to execute this program that is stored in the file.  (that is, the term we use for filename becomes the ne wcommand that matlab associates with the program). The file extension of .m makes this a MATLAB m file.  

2. M-files can be scripts that simply execute a series of  MATLAB statements, or they can be functions that also accept input arguments and produce output.  

3. The process looks like this:  

                             a. Create an M-file using a text editor  

                                                                                             function c = myfile(a, b)  

                                                                                             c = sqrt((a.^2) + (b.^2))  

                            b. Call the M file from command line or from within another M file  

                                                                                            a = 7.5  

                                                                                            b = 3.342  

                                                                                           c = myfile(a,b)  

                                                                                           c = 8 .2109  

4. Kinds of M file  

                        a. Script M files  

                       –>  Donot accept input arguments or retuen output arguments  

                      –>  Operate on data in the workspace  

                      –>  Usefule for  automating a series of steps that needed to be performed several times  

                      b. Function M-files  

                     –>    Can accept input arguments or return output  

                   –>      Internal variables are local to the function by default  

                 –>      Useful for extending the MATLAB language to yur application  

3. Example:  

                             function f = fact(n)                                                             function definition line  

                            % FACT factorial                                                                 H1 line  

                            % fact(n) returns the factorial of n                                   Help Text  

                            f = prod(1:n);                                                                       function body  

4.            edit foo  –  to open the file foo.m in the edit mode  

                list the name of files in your current directory      ——– what  

               list the contents of M file fact.m ————————–type fact  

               call the fact function            ——————————-  fact(5)  

                                                                                                                       ans = 120  

4.  Note :    

Save any M-files you create and any MathWorks-supplied M-files that you edit in a directory that is not in the $matlabroot/toolbox directory tree  

If you keep your files in $matlabroot/toolbox directories, they may be overwritten when you install a new version of MATLAB.   

Also note that locations of files in the $matlabroot/toolbox directory tree are loaded and cached in memory at the beginning of each MATLAB session to improve performance.   

If you save files to $matlabroot/toolbox directories using an external editor, or if you add or remove files from these directories using file system operations, enter the commands  

clear functionname and rehash toolbox before you use the files in the current session.   


5.   Scripts are the simplest kind of M-file because they have no input or output arguments. They are useful for automating series of MATLAB commands, such as computations that you have to perform repeatedly from the command line.  

Scripts operate on existing data in the workspace, or they can create new data on which to operate. Any variables that scripts create remain in the workspace after the script finishes so you can use them for further computations.  


6.  Simple Script Example  








These statements calculate rho for several trigonometric functions of theta then create a series of polar plots.  

% An M-file script to produce                                  % Comment lines  

 % flower petalplots  

theta = -pi:0.01:pi;                                                    % Computations  

rho(1,:) = 2 * sin(5 * theta) .^ 2;  

rho(2,:) = cos(10 * theta) .^ 3;  

rho(3,:) = sin(theta).^2;  

rho(4,:) = 5 * cos(3.5 * theta) .^ 3;  

for k = 1:4  

polar(theta, rho(k,:)) % Graphics output  




Try entering these commands in an M-file called petals.m. This file is now a MATLAB script. Typing petals at the MATLAB command line executes the statements in the script.  




After the script displays a plot, press Enter or Return to move to the next plot. There are no input or output arguments;  petals  creates the variables it needs in the MATLAB workspace. When execution completes, the variables (i, theta and rho) remain in the workspace. To see a listing of them, enter whos  at the command prompt.  

7.  Functions are M-files that accept input arguments and return output arguments. They operate on variables within their own workspace. This is separate from the workspace you access at the MATLAB command prompt.  

8.  Simple Function Example  





The average  function is a simple M-file that calculates the average of the elements in a vector.  


function y = average(x)                                                                                  

% AVERAGE Mean of vector elements.  

% AVERAGE(X), where X is a vector, is the mean of vector elements.  

% Nonvector input results in an error.  

[m,n] = size(x);  

if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))  

error(‘Input must be a vector’)  


y = sum(x)/length(x);                                                                     % Actual computation  


If you would like, try entering these commands in an M-file called average.m. The average function accepts a single input argument and returns a single output argument. To call the average function, enter  


z = 1:99;  


ans =  



9.  The Function Name:  MATLAB function names have the same constraints as variable names. The name must begin with a letter, which may be followed by any combination of letters, digits, and underscores. Making all letters in the 

name lowercase is recommended as it makes your M-files portable between platforms. 

Although function names can be of any length, MATLAB uses only the first N characters of the name, (where N is the number returned by the function namelengthmax), and ignores the rest. Hence, it is important to make each 

function name unique in the first N characters. 

N = namelengthmax 

N = 63 

The name of the text file that contains a MATLAB function consists of the function name with the extension .m  appended. For example, 


If the filename and the function definition line name are different, the internal (function) name is ignored. Thus, if average.m is the file that defines a function named compute_average, you would invoke the function by typing 


While the function name specified on the function definition line does not have to be the same as the filename, we strongly recommend that you use the same name for both. 

10. Function Arguments: If the function has multiple output values, enclose the output argument list in square brackets. Input arguments, if present, are enclosed in parentheses. Use commas to separate multiple input or output arguments. Heres a more complicated example. 

function [x, y, z] = sphere(theta, phi, rho) 

If there is no output, leave the output blank  

function printresults(x) 

or use empty square brackets 

function [] = printresults(x) 

The variables that you pass to the function do not need to have the same name as those in the function definition line. 


The H1 line, so named because it is the first help text line, is a comment line immediately following the function definition line. Because it consists of  comment text, the H1 line begins with a percent sign,  %. 

For the average function, the H1 line is % AVERAGE Mean of vector elements. 

This is the first line of text that appears when a user types help functionname at the MATLAB prompt. Further, the  lookfor  function searches on and displays only the H1 line. Because this line provides important summary 

information about the M-file, it is important to make it as descriptive as possible. 

12. Help Text 

You can create online help for your M-files by entering help text on one or more consecutive comment lines at the start of your M-file program. MATLAB considers the first group of consecutive lines immediately following the H1 line 

that begin with % to be the online help text for the function. The first line without % as the left-most character ends the help. 

The help text for the average function is 

% AVERAGE(X), where X is a vector, is the mean of vector elements. 

% Nonvector input results in an error. 

When you type   

help functionname, MATLAB displays the H1 line followed by the online help text for that function. The help system ignores any comment lines that appear after this help block. 


13.  How Functions Work 

You can call function M-files from either the MATLAB command line or from within other M-files. Be sure to include all necessary arguments, enclosing input arguments in parentheses and output arguments in square brackets. 

Posted in Matlab | Leave a comment

Controls tutorial for matlab

PID TutorialIntroduction
The three-term controller
The characteristics of P, I, and D controllers
Example Problem

Open-loop step response
Proportional control
Proportional-Derivative control
Proportional-Integral control
Proportional-Integral-Derivative control

General tips for designing a PID controller

Key Matlab Commands used in this tutorial are:




Note: Matlab commands from the control system toolbox are highlighted in red.


This tutorial will show you the characteristics of the each of proportional (P), the integral (I), and the derivative (D) controls, and how to use them to obtain a desired response. In this tutorial, we will consider the following unity feedback system:

    Plant: A system to be controlled
    Controller: Provides the excitation for the plant; Designed to control the overall system behavior

The three-term controller

The transfer function of the PID controller looks like the following:


  • Kp = Proportional gain
  • KI = Integral gain
  • Kd = Derivative gain

First, let’s take a look at how the PID controller works in a closed-loop system using the schematic shown above. The variable (e) represents the tracking error, the difference between the desired input value (R) and the actual output (Y). This error signal (e) will be sent to the PID controller, and the controller computes both the derivative and the integral of this error signal. The signal (u) just past the controller is now equal to the proportional gain (Kp) times the magnitude of the error plus the integral gain (Ki) times the integral of the error plus the derivative gain (Kd) times the derivative of the error.

This signal (u) will be sent to the plant, and the new output (Y) will be obtained. This new output (Y) will be sent back to the sensor again to find the new error signal (e). The controller takes this new error signal and computes its derivative and its integral again. This process goes on and on.

The characteristics of P, I, and D controllers

A proportional controller (Kp) will have the effect of reducing the rise time and will reduce ,but never eliminate, the steady-state error. An integral control (Ki) will have the effect of eliminating the steady-state error, but it may make the transient response worse. A derivative control (Kd) will have the effect of increasing the stability of the system, reducing the overshoot, and improving the transient response. Effects of each of controllers Kp, Kd, and Ki on a closed-loop system are summarized in the table shown below.

CL RESPONSE RISE TIME OVERSHOOT SETTLING TIME S-S ERROR Kp Decrease Increase Small Change Decrease Ki Decrease Increase Increase Eliminate Kd Small Change Decrease Decrease Small Change

Note that these correlations may not be exactly accurate, because Kp, Ki, and Kd are dependent of each other. In fact, changing one of these variables can change the effect of the other two. For this reason, the table should only be used as a reference when you are determining the values for Ki, Kp and Kd.

Example Problem

Suppose we have a simple mass, spring, and damper problem.

The modeling equation of this system is

(1)Taking the Laplace transform of the modeling equation (1)

The transfer function between the displacement X(s) and the input F(s) then becomes


  • M = 1kg
  • b = 10 N.s/m
  • k = 20 N/m
  • F(s) = 1

Plug these values into the above transfer function

The goal of this problem is to show you how each of Kp, Ki and Kd contributes to obtain

  • Fast rise time
  • Minimum overshoot
  • No steady-state error

Open-loop step response

Let’s first view the open-loop step response. Create a new m-file and add in the following code:

    num=1; den=[1 10 20]; step(num,den)

Running this m-file in the Matlab command window should give you the plot shown below.

The DC gain of the plant transfer function is 1/20, so 0.05 is the final value of the output to an unit step input. This corresponds to the steady-state error of 0.95, quite large indeed. Furthermore, the rise time is about one second, and the settling time is about 1.5 seconds. Let’s design a controller that will reduce the rise time, reduce the settling time, and eliminates the steady-state error.

Proportional control

From the table shown above, we see that the proportional controller (Kp) reduces the rise time, increases the overshoot, and reduces the steady-state error. The closed-loop transfer function of the above system with a proportional controller is:

Let the proportional gain (Kp) equals 300 and change the m-file to the following:

    Kp=300; num=[Kp]; den=[1 10 20+Kp]; t=0:0.01:2; step(num,den,t)

Running this m-file in the Matlab command window should gives you the following plot.


Note: The Matlab function called cloop can be used to obtain a closed-loop transfer function directly from the open-loop transfer function (instead of obtaining closed-loop transfer function by hand). The following m-file uses the cloop command that should give you the identical plot as the one shown above.

    den=[1 10 20];
    step(numCL, denCL,t)

The above plot shows that the proportional controller reduced both the rise time and the steady-state error, increased the overshoot, and decreased the settling time by small amount.

Proportional-Derivative control

Now, let's take a look at a PD control. From the table shown above, we see that the derivative controller (Kd) reduces both the overshoot and the settling time. The closed-loop transfer function of the given system with a PD controller is:

Let Kp equals to 300 as before and let Kd equals 10. Enter the following commands into an m-file and run it in the Matlab command window.

    Kp=300; Kd=10; num=[Kd Kp]; den=[1 10+Kd 20+Kp]; t=0:0.01:2; step(num,den,t)


This plot shows that the derivative controller reduced both the overshoot and the settling time, and had small effect on the rise time and the steady-state error.

Proportional-Integral control

Before going into a PID control, let's take a look at a PI control. From the table, we see that an integral controller (Ki) decreases the rise time, increases both the overshoot and the settling time, and eliminates the steady-state error. For the given system, the closed-loop transfer function with a PI control is:

Let's reduce the Kp to 30, and let Ki equals to 70. Create an new m-file and enter the following commands.

    Kp=30; Ki=70; num=[Kp Ki]; den=[1 10 20+Kp Ki]; t=0:0.01:2; step(num,den,t)

Run this m-file in the Matlab command window, and you should get the following plot. 

We have reduced the proportional gain (Kp) because the integral controller also reduces the rise time and increases the overshoot as the proportional controller does (double effect). The above response shows that the integral controller eliminated the steady-state error.

Proportional-Integral-Derivative control

Now, let's take a look at a PID controller. The closed-loop transfer function of the given system with a PID controller is:

After several trial and error runs, the gains Kp=350, Ki=300, and Kd=50 provided the desired response. To confirm, enter the following commands to an m-file and run it in the command window. You should get the following step response.

    num=[Kd Kp Ki];
    den=[1 10+Kd 20+Kp Ki];


Now, we have obtained the system with no overshoot, fast rise time, and no steady-state error.

General tips for designing a PID controller

When you are designing a PID controller for a given system, follow the steps shown below to obtain a desired response.

  1. Obtain an open-loop response and determine what needs to be improved
  2. Add a proportional control to improve the rise time
  3. Add a derivative control to improve the overshoot
  4. Add an integral control to eliminate the steady-state error
  5. Adjust each of Kp, Ki, and Kd until you obtain a desired overall response. You can always refer to the table shown in this "PID Tutorial" page to find out which controller controls what characteristics.

Lastly, please keep in mind that you do not need to implement all three controllers (proportional, derivative, and integral) into a single system, if not necessary. For example, if a PI controller gives a good enough response (like the above example), then you don't need to implement derivative controller to the system. Keep the controller as simple as possible.

Posted in Matlab | Leave a comment

Matlab Interview questions links

try this:

1. What can we use Matlab for?
1. Simple calculations 2. Plotting and analyzing mathematical relationships (2D and 3D) 3. List & Matrix Operations 4. Writing script files (a type of programming) 5. Symbolic manipulation of equations 6. Advanced visualization, animation and GUI interface tools
2. Vectorization What is that ? How to do it ?
Thinking is terms of full matrices/vectors and also some related functions for that * Use of filter(), which works beautifully for some time series models
3. On what machines Matlab should be run
Run it from sthelens, and only if sthelens is down, from cher, orsay or tiree. It works on other machines too, but some of the other machines have older versions of the OS and core dump upon exiting from matlab. Some other local machines with new setups work fine. Try your local machine. Matlab is blocked from running on the servers
4. LaTeX in Matlab
Matlab already handles naturally simple LaTeX encodings that allow introducing Greek lettters or modifying the font size and appearance in plots.
5. can we run Matlab without graphics?
Sometimes you may want to run scripts which contain plotting commands without displaying the plots and without going into the script to comment out the commands. An example: if you’re working from home and it’s too slow to run graphics over the network. You can play a simple UNIX trick: % setenv DISPLAY /dev/null % matlab
6. How to correctly apply the graphics patches?
# Open a LOCAL MACHINE window and type: xhost +ashland # Add the following code sequence just before the plot command that was giving you problems: figure; set(gcf,’renderer’,’zbuffer’); [s,w] = unix(‘echo $DISPLAY’); set(gcf,’XDisplay’,w);
7. how to Add noise to an image?
The function noise.m, now installed on ashland too, adds Gaussian, uniform, salt and pepper, additive or multiplicative noise to an image.
8. how to call matlab in batch mode?
his can be done from the command line or from a makefile. You need a script (filename.m). Just type at the command line, or include in the makefile: matlab<filename.m where filename.m can write to disk a figure, a binary, an ascii file, anything you want.

Posted in Matlab | Leave a comment


1. A Continuous system is a system that may be represented using differential equations

2. A discrete system is represented using difference equations

3. A hybrid system contains continuous and discrete components. A typical hybrid system would consist of a continuous process controlled by a digital computer.

Continuous Systems

Most physical blocks are modeled as continuous systems, because they can be described using differential systems. The simplest models are linear and Time invariant.

Four primitive blocks are used to represent continuous linear systems.

these are the gain block, the sum block, the derivative block and the integrator.

Any system that can be described using linear differential equations may be modeled using these four primitive blocks.

In addition to these ffour primitive blocks, the transfer function block is frequently used in the modelling of physical systems and controllers.

Gain Blocks:

The output of the gain block is the input multiplied by a constant.

Thus the block represents the algebraic equation   y = kx

A simple physical example of a gain block is the force balance of a lever.

Fig 2.2 : Lever force multiplication

the lever in equilibrium can be represented by the equation

Fout = a Fin

where a is the lenght ratio.

a = l1 / l2

Other physical examples that would be represented using gain blocks are the linear model of an electrical resistor and the linear spring. The equation for the linear resistor is

v = RI

in which the input is the current I, the gain is the resistance R, and the output is the voltage v. The behaviour of a linear elastic spring is represented by the equation

F = kx

where the input is the spring deflection x, the gain is the spring constant k, and the output is the force F.

Sum Block

The sum block permits us to add two or more inputs. The output of the sum block is the algebraic sum of the inputs. Each input is labeled with a plus (+)  signor a minus (-) sign to indicate whether the input is to be added or subtracted.

Exampe: c = a -b

Derivative Block:

The derivative block computes the time rate of change of its input . The block represents the differential equation

y = dx/dt

A physical example of a system componenet the could be represented using a derivative block is a dashpot. The force equation of a dashpot is

  F = c dx/dt

where F is the damping force and C is the damping coefficient.


The integrator block computes the time integral of its input from the starting time to the present.

The integrator block represents the equation

y(t) = y(t0) + ∫x(τ)dτ

Posted in Simulink | Leave a comment

loopsens – Sensitivity functions of plant-controller feedback loop

loopsens – Sensitivity functions of plant-controller feedback loop


loops = loopsens(P,C)


loops = loopsens(P,C) creates a struct, loops, whose fields contain the multivariable sensitivity, complementary and open-loop transfer functions. The closed-loop system consists of the controller C in negative feedback with the plant P. C should only be the compensator in the feedback path, not any reference channels, if it is a 2-dof controller as seen in the figure below. The plant and compensator P and C can be constant matrices, double, lti objects, frd/ss/tf/zpk, or uncertain objects umat/ufrd/uss.

The loops returned variable is a structure with fields:

Field Description
Poles Closed-loop poles. NaN for frd/ufrd objects
Stable 1 if nominal closed loop is stable, 0 otherwise. NaN for frd/ufrd objects
Si Input-to-plant sensitivity function
Ti Input-to-plant complementary sensitivity function
Li Input-to-plant loop transfer function
So Output-to-plant sensitivity function
To Output-to-plant complementary sensitivity function
Lo Output-to-plant loop transfer function
PSi Plant times input-to-plant sensitivity function
CSo Compensator times output-to-plant sensitivity function


The multivariable closed-loop interconnection structure, shown below, defines the input/output sensitivity, complementary sensitivity, and loop transfer functions.

Description Equation
Input sensitivity ( ) (I+CP)–1
Input complementary sensitivity ( ) CP(I+CP)–1
Output sensitivity ( ) (I+PC)–1
Output complementary sensitivity ( ) PC(I+PC)–1
Input loop transfer function CP
Output loop transfer function PC



Single Input, Single Output (SISO)

Consider PI controller for a dominantly 1st-order plant, with the closed-loop bandwidth of 2.5 rads/sec. Since the problem is SISO, all gains are the same at input and output.

gamma = 2; tau = 1.5; taufast = 0.1; 
P = tf(gamma,[tau 1])*tf(1,[taufast 1]); 
tauclp = 0.4; 
xiclp = 0.8; 
wnclp = 1/(tauclp*xiclp); 
KP = (2*xiclp*wnclp*tau - 1)/gamma; 
KI = wnclp^2*tau/gamma; 
C = tf([KP KI],[1 0]);

Form the closed-loop (and open-loop) systems with loopsens, and plot Bode plots using the gains at the plant input.

loops = loopsens(P,C); 

Finally, compare the open-loop plant gain to the closed-loop value of PSi


Multi Input, Multi Output (MIMO)

Consider an integral controller for a constant-gain, 2-input, 2-output plant. For purposes of illustration, the controller is designed via inversion, with different bandwidths in each rotated channel.

P = ss([2 3;-1 1]); 
BW = diag([2 5]); 
[U,S,V] = svd(P.d);  % get SVD of Plant Gain 
Csvd = V*inv(S)*BW*tf(1,[1 0])*U'; % inversion based on SVD 
loops = loopsens(P,Csvd); 

Posted in Matlab | Leave a comment