You are on page 1of 73



Short Term Course on application of Soft Computing tools in
the field of science and Technology, 2013 (STCSCT2013)




 Introduction

Main Features of MATLAB
MATLAB Desktop
Data types supported by MATLAB
Operators Supported
How to read a matrix?
Elementary Mathematical Functions
2D and 3D Graphics
Generation of m-file




 MATLAB – A product by Mathworks is high performance

language for technical computing that integrates
computation, visualization and programming.
 MATLAB is developed in the late 1970’s by Cleve Moler,
chairman of the computer science department at the
University of New Mexico.
 Initially it was developed to perform numerical
calculations on vectors and matrices.
 Matlab is now used for mathematical calculations and
simulations in companies and government labs ranging
from aerospace, car design, signal analysis to instrument
control and financial analysis.



17/6/2013 STCSCT2013 4 . real matrices and complex matrices are all automatically handled as special cases of the basic data-object. Scalars.  Vectors. MATrix LABoratory  Matrices are the basic building blocks in MATLAB  Thus the fundamental numeric data object in MATLAB is the array. The name MATLAB is the combination of two terms.

 The language. 17/6/2013 STCSCT2013 5 .  Graphics.Main features of MATLAB The Complete MATLAB set up consists of:  Desktop tools and Development Environment.  Documentations.  Mathematical Function Library.  External Interfaces.

 Workspace: It includes the names of variable generated during the running of certain functions and codes.  Command History: It provides all the details of the functions typed and codes executed.MATLAB DESKTOP  The MATLAB desktop consists of:  Command Window: Simple basic operations can be done. 17/6/2013 STCSCT2013 6 .  Current Directory: It shows the location from where the program is running.  Help Browser: It is the way to go through the details of the documentation.

17/6/2013 STCSCT2013 7 .

there is no need to declare variables as real or complex.e. MATLAB automatically sets the data types of variables. whatever the data type.  The simplicity with MATLAB is that. 17/6/2013 STCSCT2013 8 .Data types Supported By MATLAB  The data types supported by MATLAB are constant and variable.  The complete list of data types supported by MATLAB can be generated by typing help datatypes in the command window. users never need to worry about its declaration i.  Among variables the supported types are integer. character and strings. floating point.

Table1: Data types supported by MATAB 17/6/2013 STCSCT2013 9 .

17/6/2013 STCSCT2013 10 . • MATLAB is case sensitive. therefore A and a are different variables in MATLAB.Rules for Variable Assignment • Variables in MATLAB are named objects that are assigned using the equals sign = . which may be followed by any combination of upper and lowercase letters. • MATLAB variable names must begin with a letter. digits and underscores.

MATLAB uses only the first N characters of the name and ignores the rest. >> N = namelengthmax N = 63 Hence. Although variable names can be of any length. which is a built in function in MATLAB. it is important to make each variable name unique in the first N characters to enable MATLAB to distinguish variables. 17/6/2013 STCSCT2013 11 . returns the maximum length allowed for MATLAB identifiers. N is the number returned by the function namelengthmax.

a list of m-functions will be displayed with name sin. Users should avoid using i and j for variable names if they intend to use them in complex arithmetic. user can use the command.  MATLAB uses the characters i and j to represent imaginary units. otherwise that function is not allowed to call until the variable is cleared from memory.  To test whether a proposed variable name is already used as a function name. Variable name should not be same with any existed function name. >> which -all sin On pressing enter key. 17/6/2013 STCSCT2013 12 .

Operators Supported MATLAB supported an extensive number of operators. These are:  Arithmetic Operators  Relational Operators  Logical Operators  Bitwise Operators  Set Operators 17/6/2013 STCSCT2013 13 .

Arithmetic Operators  MATLAB supports two different types of arithmetic operations-     i) Matrix arithmetic operations ii) Array arithmetic operations Matrix arithmetic operations are defined by the rules of linear algebra. 17/6/2013 STCSCT2013 14 . Array arithmetic operations are carried out element by element and can be used with multidimensional arrays The period character (.) distinguishes the array operations from the matrix operations. For on-line help to see arithmetic operators type help arith.

Any scalar (a 1-by1 matrix) may multiply anything.*Y denotes element-by-element multiplication. X*Y is the matrix product of X and Y.* Array multiplication X. 17/6/2013 STCSCT2013 15 . the number of columns of X must equal the number of rows of Y. Otherwise. A scalar can be multiplied into anything. Matrix multiplication.  . X and Y must have the same dimensions unless one is a scalar.

Relational Operators  Relational operators are used to establish relation      between variables. <=. and >= use only the real part of their operands for the comparison. The operators == and ~= test real and imaginary parts. >. Relational operators perform element-by-element comparisons between two arrays. 17/6/2013 STCSCT2013 16 . with elements set to logical 1 (true) where the relation is true. For help type help relop. The operators <. and elements set to logical 0 (false) where it is not. They return a logical array of the same size.

and ~ are the logical array operators AND.  The symbols &. OR and NOT. |.  It returns logical 0 representing false and logical 1 or any nonzero element representing true. 17/6/2013 STCSCT2013 17 .Logical Operators  Logical operators perform boolean/logical operation on variables.  They work element by element on arrays.  For help type help relop.

 For help type help ops. OR.Bitwise Operators  Bitwise operators are used to perform bitwise logical AND. XOR and shifting operations. 17/6/2013 STCSCT2013 18 . NOT.

line help type help ops 17/6/2013 STCSCT2013 19 . like union. intersection etc.Set Operators  MATLAB provides a set of operators for performing set operations vectors. between  For on.

4 5 6] ans = 1 2 3 4 5 6 .  Elements of the matrix may be real numbers.  For example. >> [4 5 6] ans = 4 5 6 >> [1 2 3. with consecutive elements of a row separated by a space or a comma.How to Read Matrix in MATLAB?  In MATLAB matrix is entered row-wise.  The entire matrix must be enclosed within square brackets. complex numbers or valid MATLAB expressions. and the rows separated by semicolons or carriage returns.

with just one row or one column. .3] v= 1 2 3 v is a column vector. For examples.2. It is entered the same way as a matrix. Vector is a special case of matrix. >> v=[1. >> u=[1 2 3] u= 1 2 3 u is row vector.

 If we need to create a vector of numbers over a given range with a specified increment. MATLAB has a general command to this as v=Initial value: Increment: Final value For example. >> 0:10:100 ans = 0 10 20 30 40 50 60 70 80 90 100 .

N) . Logspace (X1. 20. 5) u = 0 5 10 15 20 >> u=logspace(0. 3. X2. 4) u = 1 10 100 1000 .b.n) – it generates linearly spaced vector of length n from a to b. MATLAB has two built in functions which is most frequently used to generate vectors: linspace and logspace linspace (a.generates a row vector of length N logarithmically equally spaced points between decades 10^X1 and 10^X2 For example >> u=linspace(0.

e. >> g= 2. A scalar does not need brackets. For example. For example. with dimension 1×1.1000  Square brackets with no elements between them create a null matrix.1 g = 2. >> x= [ ] x = [ ] . Scalar is matrix with one element i.

 Unlike other software packages and programming language MATLAB allows the user to specify a range of rows and columns to specify at the same time. k:l) specify rows m to n and column k to l of matrix A. For example.j) in MATLAB refers to the element of the ith row and jth column. A(m:n. . A(:.k:l) refers to the elements in the column k through l of all the rows of matrix A.Indexing or Subscripting and Dimensions  User can access the elements of matrix by specifying their row and column indices. A(i. For example.

 MALAB automatically determines the matrix

 To check the dimension of an existing matrix user
can use the command
it will assign the numbers of rows and columns of
A to the variables m and n respectively.
 Command length(A) returns the length of vector
 length(A) is equivalent to max(size(A)) for nonempty arrays and 0 for empty ones.

Matrix Handing Operations and Functions
 Reshaping Matrices:

1] All the elements of a matrix A can be put into a singlecolumn vector by the command b=A(:).
2] reshape(x, m, n)-Returns the m-by-n matrix
whose elements are taken column wise from x.
An error results if x does not have m×n elements.

 Transpose of Matrices: Transpose of matrix A is obtained by typing

>> A=[1 2 3; 4 5 6]
A =
>> B=A'
B =

Initialization: Normally initialization is not needed in MATLAB.
1. If a large matrix is to be generated, then a zero matrix of
required dimension is recommended to initialize. It will reserve
a contiguous block for the matrix in the computer memory.
2. Similarly if rows and columns of the matrix are computed in a
loop and appended to the matrix in each execution of the loop,
it is recommended to initialize the matrix to a null matrix
before the loop starts. It will allow the user to append a row or
column of any size.

 Appending a row or column: Any row or column can be easily appended to an existing matrix.:)=[ ] .It will append the column vector u to the columns of A A=[A . Example: A=[A u].Deletes the 3rd through 5th column of A . Example. v]. A row or column of any size can be appended to a null matrix. provided the row or column has the same length of the existing matrix.It will appends the row vector v to the rows of A.  Deleting a row or column: Any row or column of matrix can be deleted by setting the row or column to a null vector .Deletes the 2nd row of matrix A A(:. A(2.3:5)=[ ] .

A few of them are:  X=magic(m): creates a m x m square matrix with equal row and column and column sums.HANDLING MATRICES  Many built in functions are there in MATLAB to create and manipulate matrices and carry out all the operations. 17/6/2013 STCSCT2013 30 .  A= rand (n) creates a matrix of size n x n of random values from a uniform distribution.  B= randn(4) creates matrix 4 x 4 containing pseudo random values from a normal distribution with mean zero and standard deviation one.

 D= zeros(N): generates a matrix of size N x N containing zeros only.  E= eye(N): generates a identity matrix of size N x N with ones in the diagonal and zeros every where. C=ones(3) : generates a matrix of size 3 x 3 containing ones only. 17/6/2013 STCSCT2013 31 .

ELEMENTATARY MATHEMATICAL FUNCTIONS  TRIGONOMETRIC FUNCTIONS  EXPONENTIAL FUNCTIONS  COMPLEX  ROUNDING and REMAINDER  In the Command window type help elfun to get the details of mathematical functions. 17/6/2013 STCSCT2013 32 .

Inverse cosine.Inverse sine.Tangent. .Inverse hyperbolic sine.Hyperbolic sine.Some of the trigonomeric functions:               17/6/2013 sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand . . result in degrees.Inverse hyperbolic cosine. . . . STCSCT2013 33 . . .Inverse cosine. .Tangent of argument in degrees.Cosine of argument in degrees. .Sine of argument in degrees.Inverse sine. result in degrees. . .Hyperbolic cosine.Sine. .Cosine. .

log2 .Applications of exponential functions        exp . expm1 .Common (base 10) logarithm.Natural logarithm. log10 . 17/6/2013 STCSCT2013 34 . pow2 .Compute log(1+x) accurately.Compute exp(x)-1 accurately. log1p .Base 2 logarithm and dissect floating point number.Base 2 power and scale floating point number. log .Exponential.

Phase angle.Absolute value.Use of Complex functions          abs . angle . imag .Unwrap phase angle. isreal . complex . cplxpair . unwrap .True for real array.Sort numbers into complex conjugate pairs.Construct complex data from real and imaginary parts.Complex conjugate. real . conj .Complex real part.Complex imaginary part. 17/6/2013 STCSCT2013 35 .

Round towards plus infinity.Remainder after division. rem sign 17/6/2013 .Rounding and remainder. . .        fix floor ceil round mod division). . .Round towards minus infinity.Round towards nearest integer.Modulus (signed remainder after . STCSCT2013 36 .Signum.Round towards zero. .

besselj .Bessel functions of the third kind (Hankel function). erf .Modified Bessel function of the first kind. betainc . besselk .Logarithm of beta function.Complete elliptic integral.Error function. beta .Incomplete beta function.Modified Bessel function of the second kind.Bessel function of the second kind. betaln . 17/6/2013 STCSCT2013 37 .Beta function. besselh . besseli .Specialized Mathematical functions  To get the details of these functions type help specfun in the command             window.Airy functions. airy .Jacobi elliptic functions. bessely . ellipke . ellipj .Bessel function of the first kind.

           17/6/2013 erfc . legendre .Vector cross product.Inverse error function.Incomplete gamma function. psi .Logarithm of gamma function.Complementary error function. dot .Gamma function. erfcx .Associated Legendre function. cross .Scaled complementary error function.Psi (polygamma) function.Vector dot product.Exponential integral function. gamma . gammainc . expint . erfinv . gammaln . STCSCT2013 38 .

17/6/2013 STCSCT2013 39 .Input and Output Handling in MATLAB  Input() X= input(‘ Give the input’)  Disp() If X= Result and disp(‘the sum is’) then disp(x) will show the string and the result.

17/6/2013 STCSCT2013 40 .coordinate points yvalues: Vectors containing y-coordinates points style-option: An optional argument that specifies the color. plot(xvalues.  The main tool of MATLAB graphics is the plot command bearing syntax. point mark style etc.  The vectors xvalues and yvalues must have the same length. yvalues. xvalues: Vectors containing x. the line style.TWO DIMENSIONAL AND THREE DIMENSIONAL GRAPHICS  All graphical images are generated in a separate “graphics window". `style-options’) where.

plot (x. Colors. plot(x.Style Options  There are many style options for changing the appearance of a plot. To plot the points using blue crosses without joining them with lines.’) 2.’r-. .y.’bx’) 3.y. symbols and lines can be combined. and plot(x. To join the points using a red dash-dotted line.y.’b:x’) 4. For example: 1. To plot the points using blue crosses and joins them with a blue dotted line.

m C W magenta (1 0 1) cyan (0 1 1) white (1 1 1) k black (0 0 0) solid line (default) dashed line dotted line dash-dot line Marker-style Option + plus sign O * . circle asterisk point x cross s d ^ < square diamond upward pointing triangle downward pointing triangle right pointing triangle left pointing triangle p pentagram h hexagram v > TABLE 11: STYLE OPTIONS IN MATLAB .Color style Option Line-style Option r red (1 0 0) - g B y green (0 1 0) blue (0 0 1) yellow (1 1 0) -: -.


.  To get rid of all the figure windows.Clearing and Creating the Figure Window  User can clear the plot window by typing clf. which stands for ‘clear figure’. close all is used.  To get rid of a figure window entirely.  New figure windows can be created by typing the command figure before using the plot command. user can type close.

Text and Legend  Subplot: To plot more than one set of axes in the same window. Titles. Labels.n.Subplots. subplot command is used. Syntax: subplot (m.p) which breaks up the ploting window into m plots in the vertical direction and n plots in the horizontal direction. . choosing the pth plot for drawing into.


.titles the plot with text text(x.y.’text’) -places text at position x. y gtext(’text’) .labels the x-axis with text ylabel(’text ’) .labels the y-axis with text title(’text’) . titles and text on a plot by using the commands: xlabel(’text ’) .use mouse to place text . User can put labels.


. Legend: Legend on plots can be produced using the Insert-     legend button in the figure window toolbar or with the legend command.string3. . . Legend command can take several optional arguments.. The most common commands are listed below: legend(string1.)-Puts a legend on the plot containing the handles in the vector h using the specified strings as labels for the corresponding handles. legend(h.Removes the legend from the current axes and deletes the legend handle.string2.Puts a legend on the current plot using the specified strings as labels. ..string3.string1.) ..string2. legend off. The legend command produces a boxed legend on a plot.

n.x1. % fun_4 plot(n.'om'). legend('fun_1'.x2. % fun_2 x3=5*exp(-n).length(n)).'fun_3'.>> n=1:10. % fun_3 x4=rand(1. title('plot with legend'). % fun_1 x2=log10(n).'fun_4').'fun_2'.'-.'-k'.b'.x3.n. x1=log(n).x4. .n.'-ro'.


Maximum values for x-axis and y-axis  There are also some useful predefined string arguments for the axis command: axis(‘equal’).sets equal scale on both axes axis(‘square’).removes the surrounding frame and the tick marks .sets the default rectangular frame to a square axis(‘normal’). Syntax: axis([xmin xmax ymin ymax]) xmin.freezes the current axes limits axis(‘off’).Axis: In MATLAB once plot is generated axis function can be used to change axis limits. ymax.Minimum values for x-axis and y-axis xmax. ymin.resets the axis to default values axis(‘axis’).

For example. The axis command must come after the plot command to have the desired effect. axis([-5 10 –inf inf]) axis([-5 inf -inf 22]) 17/6/2013 STCSCT2013 53 .  At times it is possible to control a part of the axes limits and let MATLAB set the other limits automatically.

adds the line in vectors X and Y to the current axes. Syntax: hold. 2. plot command itself. line(x. 3.Overlay plots:  MATLAB provides three different commands of generating overlay plots. hold off. line command. 1. .Holds the current plot and all axis properties so that subsequent graphing commands add to the existing graph.y).Hold current graph hold on. hold command.returns to the default mode whereby PLOT commands erase the previous plots and reset all axis properties before drawing new plots.

text etc.y. y and z are three vectors of the same length.el) where.  Plots in 3-D can be annotated with functions already mentioned for 2D plots like xlabel.Three-Dimensional Plots The plot3 command is used for visualizing three-dimensional  graphics. title. plots a line in 3-space through the points whose coordinates are the elements of x.  MATLAB provides a very important command view to specify the viewing angle for an observer.z) where x. Syntax: plot3(x. Syntax: view(az. argument az is the azimuth angle and el is the elevation angle. y and z. 17/6/2013 STCSCT2013 55 . ylabel.

2.2.ylabel('cos(t)').f2. figure. xlabel('sin(t)'). subplot(2. f1=sin(t).4).t). subplot(2.90). subplot(2.3). title('projection in the Y-Z plane').f2.>> t=0:pi/70:15*pi.zlabel('t').t).plot3(f1.t). grid on. title('projection in the X-Z plane'). title('A circular helix').view(90. xlabel('sin(t)').t). xlabel('sin(t)').view(0.plot3(f1. .f2. f2=cos(t).0).1).2.0).2). xlabel('sin(t)').ylabel('cos(t)'). title('projection in the X-Y plane').view(0.2. axis square.plot3(f1.f2. subplot(2.plot3(f1.ylabel('cos(t)').ylabel('cos(t)').

y.  In order to visualize discrete 3-D graphics MATLAB stem3 command can be used Syntax.y) It generates a plot of discrete sequence y at the values specified in x terminated by a circle. stem(x. most frequently in applications involving digital signal processing. Syntax. MATLAB command stem can be used in the same manner as command plot. In such cases.z) 17/6/2013 STCSCT2013 57 .Plotting Discrete Data  At times it may be required to generate graphics of discrete data. stem3(x.

stem3(x. >> x=linspace(0. xlabel('t'). figure.2*pi. y=x*0.x1).0.>> t=linspace(-2*pi.75. x=tan(cos(t1)).y.ylabel('tan(cos(t))'). stem(t1. title('3-D discrete plot').20). FIGURE 8: USE OF stem COMMAND .z).5. title('use of stem'). z=2*sin(x)+3*cos(y).8).

Use of BAR.y) It draws the columns of the M-by-N matrix y as M groups of N vertical bars. bar command hist command stair command MATLAB command bar is used to present data in vertical columns. Syntax bar(x. . The vector X must not have duplicate values. HIST and STAIR  Generally three commands are used to present data in  graphics.

 Similarly. Another command hist can be used to generate histogram. which is a type of bar graphs that are created by first specifying the number of levels that specify a range of values and then counting the number of occurrences of a data set that fall within each level. . Syntax hist(y) If y is a vector with 10 values. y) can be used to draw horizontal lines at the level specified by the elements of y. it will create a histogram with 10 equally spaced bins that cover the range of values between the minimum and maximum values of the variable y. This level will be held constant over the period between the values specified by the index numbers when using stairs(y) or the elements in x when using stairs(x.y). The functions stairs(y) or stair(x. a stair plot may be used to stress the discrete nature of a data set.

30).sin(x)) title('Stair plot').5 4. title(' Histogram') Figure 9: Use of bar. 3.2:0. hist and plot command . title('Bar plot') beta=1. figure.30).n)) x=0.5 y=-beta*log(rand(1. b=linspace(2*pi. stairs(x. y). hist(y.4:10 figure.3 4.x). x=[a b]. bar(x.>> n=1000 >> x=[1 4 6 8] y= [5 2. >> a =linspace(0.2*pi. ylabel('count').4*pi.5 3] figure.

Generation of m-file .

 There is no possibility of modification in the codes.Generation of m-FILE  It is already known that using command prompt we can solve a problem.  Executed program in the command prompt can’t store for manipulation or modification .  The limitations are--- Only the shorter code can be written. But the command prompt has many limitations. .

.  Store the executed files.NEED OF M-FILE CREATION  The solution of these problem is to use matlab editor.  Generate the user defined function which reduces the code complexity and code redundancy in the main program.  In matlab editor we can write the codes and the codes can be modified in the time of writing or later.

.  Using the editor.Matlab Editor  The editor is a platform in the Matlab package by which programs can be written. modified and stored very easily. the programmer can generate the Matlab executable m-file.

Matlab Editor .

Those codes are given below clc  clear all  close all .Universal Codes for M-files  There are certain codes which are always written in m-file irrespective of programming problem.

. close all close all the open figure window. clear all clear variables and functions from memory and workspace.Universal Codes for M-files Code Function clc Clear the contents of command prompt.

. # etc.Precaution while saving the m-file  Name of the file should not start with special characters like _.  “Space” is not allowed in the m. @.  M-file name should not be similar to the built-in functions. %.file name. & .

Generation of m-file .

We have also discussed how to create an m-file. We have discussed briefly the introduction of matlab. MATLAB converts all the data into matrix or matrix arrays. different types of operators it supports. data types used. Whatever the field of application.Conclusion  Now a days MATLAB is used in every field of research     or in labs or in industry. The basic component which MATLAB deals with is the matrix. 17/6/2013 STCSCT2013 71 .

Oxford University Press. “Getting Started with MATLAB 7”. Basic concept and Applications”.References  Sarma. “MATLAB Demystified. (2010). Vikash Publication. 17/6/2013 STCSCT2013 72 .  Pratap R. K.K. .

Thank You 17/6/2013 STCSCT2013 73 .