Sunteți pe pagina 1din 66

MATrix LABoratory

MATLAB was originally developed to be a "matrix laboratory," written to provide easy access to matrix software developed by the LINPACK and EISPACK projects Matlab is used for both symbolic and numerical computation and visualization

MATLAB was invented in the late 1970s by Cleve Barry Moler, then chairman of the computer science department at the University of New Mexico

He designed it to give his students access to LINPACK and EISPACK without having to learn Fortran. It soon spread to other universities and found a strong audience within the applied mathematics community

Jack Little, an engineer along with Moler recognized its commercial potential.

He joined with Moler and Steve Bangert. They rewrote MATLAB in C and founded The MathWorks in 1984 to continue its development

MATLAB is an interactive matrix based system for scientific and engineering numerical computation simulation and visualization of problems MATLAB features a set of application specific solutions called toolboxes Toolboxes-comprehensive collection of Matlab functions(M files) Type demo matlab general at the command prompt to get a feel of the language capabilites

Toolboxes available

Matlab Development Environment(MDE)

By double clicking on the shortcut From the Run dialog It is a five panel layout with A) launchpad B)workspace variables C)command window 4)command histroy 5)current directory-workspace

SIMULINK is an interactive system for the nonlinear simulation of dynamic systems. A graphical, mouse-driven program that allows systems to be modeled by drawing a block diagram on the screen.

Simulink is a block library tool for modeling, simulating and analyzing dynamic systems. It is developed by The MathWorks and works with their flagship product, MATLAB SIMULINK is an interactive system for the nonlinear simulation of dynamic systems.

It can handle linear, nonlinear, continuous-time, discrete-time, multivariable, and multirate systems SIMULINK is fully integrated with MATLAB, and, together with MATLAB and the Control System Toolbox, forms a complete control system design and analysis environment Simulink libraries (blockset) can be invoked from the command prompt by typing simulink Type toilet at the matlab command prompt to run a simulation and feel of Simulink Type vibes to see the L shaped logo

Simulink is widely used in control theory and digital signal processing for multidomain simulation and design. Coupled with Real Time Workshop, another product from The MathWorks, Simulink can do automatic code generation for real-time implementation of systems. In addition to being a popular tool for embedded system design work because of its flexibility and capacity for quick iteration,it also supports thirdparty hardware and software products

MATLAB is the "Matrix Laboratory", and so provides many convenient ways for creating arrays of various dimensions. In the MATLAB vernacular, a vector refers to a one dimensional (1N or N1) matrix, commonly referred to as an array in other programming languages. a matrix generally refers to a multidimensional matrix, that is, a matrix with more than one dimension Unlike languages such as Java and C++, m is not statically typed, meaning that variables themselves do not have types, only the runtime values stored in those variables have types,

Besides Matlab also houses its compiler which converts the M-file into C or C++. The source code is compiled into object code using a C/C++ system compiler. The resulting code is linked with the corresponding math and graphics libraries and any application-specific files making its an application development tool

Matlab basics

Matlab programs can be run from the command line or by use of a GUI Run from the command line 2.3+4.2 Matlab woks on different types of data objects that are manipulated They are scalars ,vectors and matrices A=[1 2 3] B=[2 2;2 2]; C=2:8

M files
All functions can be combined and run as a sequential file on disk called M file Format rat-rationalize Format compact Format long Sqrt(2)

Matlab datatypes
The MATLAB language works with only a single object type: the MATLAB array. All MATLAB variables, including scalars, vectors, matrices, strings, cell arrays, structures,and objects are stored as MATLAB arrays. In MATLAB, subscripts begin at 1 rather than 0. Every MATLAB data object is an array. The twodimensional version of an array is called a matrix. MATLAB functions are vectorized.

Trigonometric functions
Cos(pi/6) Tan(pi/2) 9/0 0/0 Nan/Inf IEEE floating point

Symbolic object
Matlab can also do symbolic computation Syms a b c x F=sym(a*x^2+b*x+c) solve(F) Pretty(F)

Variable assignment
X=7 X^2+3*x+2 Log(x) Y=5*x X=x+5 Who-all variables u have created in this session whos Save as mat file Clear Load mat file

Matrices can be entered in different ways As an explicit list Inbuilt functions Loaded from the diskfile for a local editor Loaded from external data

A=[1 2 3 ;4 5 6;7 8 9] Matlab is case sensitive Size(a) A=[1 2 ; 3 4] +i[5 6;7 8]-complex no Vectors are matrices with a single row/column B=[1;2;3] W=[1 2 3 4] Define even spaced matrices-2:5 [3:2:9] A(3,2) A(3,:) A(:,3)

Command line help

Helpwin Doc Lookfor Help followed by function name

Concatenate-cat b=[2 2;4 5] A=[1 2 3; 4 5 6] [A b] Dot product and cross product A=[1; 4 ;3; 5] B=[ 7;9;5;0] Dot[A,B]=dot[B,A] Length=sqrt(dot(A,A)) Norm cosU=v.w/(length(v)*length(w))

U=[1;2;3] V=[7;8;9] Cross(U,V) Dot(cross ans and primary vectors is zero) Matrix operations A+B, 2*A Matrix building functions Eye,zeros,ones,diag,Triu,Tril,Rand,Hilb,ma gic,toeplitz

Eig ,inv,det,rank

Programming Constructs: for ,while, if

Script- is a sequence of normal matlab statements.scripts are invoked at the command line by their name Functions- are scripts with input and output arguments ,eg open m editor and type function [mean,stdev]=stat(x) % comment and help [m,n]=size(x) If m==1 m=n; End Mean=sum(x)/m Stdev= sqrt(sum(x.^2)/m mean.^2); vectorize Save as stat.m A command [a,b]=stat(c) will assign mean and standard deviation to a and b

PATH setting path and preferences C:\MATLAB6p1\toolbox\matlab\matfun Each set of functions in a specific area is called a toolbox Each toolbox will contain a contents.m which is the function summary

The data functions in matlab -Data analysis and Fourier transforms. Basic operations Finite differences. Filtering and convolution. Fourier transforms

Matfun directory
Matfun directory C:\MATLAB6p1\toolbox\matlab\matfun The matlab functions in matfun Matrix analysis Linear equations Eigenvalues and singular values Matrix functions Factorization utilities

Datatypes supported by matlab

C:\MATLAB6p1\toolbox\matlab\datatypes Data types (classes) Multi-dimensional array functions Cell array functions Structure functions Function handle functions Object oriented programming functions Overloadable operators

Stand-Alone Programs
In addition to writing M-files, there are three other ways you can call MATLAB functions:via MEXfiles or via the MATLAB Engine, or by using either the MATLAB C or C++ Math Library. Any M-file, MEX file, or Engine code you write requires the entire MATLAB environment to run. However, with the MATLAB C and C++ Math libraries, you can write stand-alone (external) programs.

Data Storage
All MATLAB data is stored columnwise. This is how Fortran stores matrices; MATLAB uses this convention because it was originally written in Fortran. For example, given the matrix a=['house'; 'floor'; 'porch']

Data Types in MATLAB

Cell Arrays- Cell arrays are a special class of MATLAB array whose elements consist of cells that themselves contain MATLAB arrays. Both structures and cell arrays provide a hierarchical storage mechanism for dissimilar kinds of data. Structures-Structures are collections of different kinds of data organized by named fields. Objects-timer ,serial objects

Cell array
You can build a cell array by assigning data to individual cells, one cell at a time. MATLAB automatically builds the array as you go along. There are two ways to assign data to cells: Cell indexing Content indexing

Enclose the cell subscripts in parentheses using standard array notation.Enclose the cell contents on the right side of the assignment statement in curlybraces, "{}. For example, create a 2-by-2 cell array A A(1,1) = {[1 4 3; 0 5 8; 7 2 9]}; A(1,2) = {'Anne Smith'}; Cell arrays in MATLAB are multidimensional arrays whose elements are copies of other arrays. A cell array of empty matrices can be created with the cell function. A = cell(8,1);

Cell indexing

Content indexing
Enclose the cell subscripts in curly braces using standard array notation. Specify the cell contents on the right side of the assignment statement. A{2,1} = 3+7i; A{8,1} = -pi:pi/10:pi;

Structures are MATLAB arrays with named "data containers" called fields The fields of a structure can contain any kind of data. For example, one field might contain a text stringrepresenting a name, another might contain a scalar representing a billing amount, a third might hold a matrix of medical test results, = 'John Doe'; patient.billing = 127.00; patient.test = [79 75 73; 180 178 177.5; 220 210 205]

Function Handles
You can create a handle to any MATLAB function and then use that handle as a means of referencing the function. A function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle. Construct a function handle in MATLAB using the at sign, @, before the function name. Evaluate a function handle using the MATLAB feval function. fhandle=@sqrt; feval(fhandle,9); feval(fhandle,25);

Function handles enable you to do all of The following: Pass function access information to other functions Allow wider access to subfunctions and private functions Ensure reliability when evaluating functions Reduce the number of files that define your functions Improve performance in repeated operations Manipulate handles in arrays, structures, and cell arrays

A Simple Function Handle

handle = @function F = functions(@disp) F=figure Get(F); Serial object ,s = serial('COM1');

Specialized functions
C:\MATLAB6p1\toolbox\matlab\specfun Specialized math functions. Number theoretic functions Coordinate transforms Others

Matfun directory
PATH :C:\MATLAB6p1\toolbox\matlab\matfun Each set of functions in a specific area is called a toolbox Each toolbox will contain a contents.m which is the function summary

General purpose
C:\MATLAB6p1\toolbox\matlab\general-General purpose commands General information Managing the workspace Managing commands and functions Managing the search path Controlling the command window Operating system commands Debugging M-files and profiling M-files. Obsolete functions Others and GUI utilities

Elementary math functions

C:\MATLAB6p1\toolbox\matlab\elfun Trigonometric Exponential Complex Rounding and remainder

Elementary matrix functions

C:\MATLAB6p1\toolbox\matlab\elmat Elementary matrices Basic array information Matrix manipulation Special variables and constants Specialized matrices and obsolete functions

C:\MATLAB6p1\toolbox\matlab\funfun Optimization and root finding Optimization Option handling Numerical integration (quadrature) Plotting and Inline function object Differential equation solvers Boundary value problem solver for ODEs.

Function functions and ODE solvers.

File input/output
C:\MATLAB6p1\toolbox\matlab\iofun File import/export functions. Image file import/export Audio file andVideo file import/export Formatted file I/O String conversion File opening and closing. Serial port support Command window I/O FIG file support for plotedit and printframes

Programming language constructs

C:\MATLAB6p1\toolbox\matlab\lang Control flow. Evaluation and execution Scripts, functions, and variables. Argument handling Message display Interactive input

Operators and special characters

C:\MATLAB6p1\toolbox\matlab\ops Arithmetic operators Relational operators Logical operators Special characters Bitwise operators Set operators and Additional help files.

Sparse matrices.
C:\MATLAB6p1\toolbox\matlab\sparfun Elementary sparse matrices Linear algebra.and Linear Equations (iterative methods) Operations on graphs (trees)

String functions-Character strings

C:\MATLAB6p1\toolbox\matlab\strfun General String tests String operations

Time and dates.

C:\MATLAB6p1\toolbox\matlab\timefun Basic functions Date functions and Timing functions

C:\MATLAB6p1\toolbox\matlab\ winfun
Windows Operating System Interface Files (DDE/ActiveX) ActiveX Client Functions. DDE Client Functions

Handle Graphics
C:\MATLAB6p1\toolbox\matlab\graphics Figure window creation and control. Axis creation and control Handle Graphics objects and operations Hardcopy and printing Printing and I/O utilities

2d graphs
C:\MATLAB6p1\toolbox\matlab\graph2d Elementary X-Y graphs Axis control Scribe utilites

Three dimensional graphs.

C:\MATLAB6p1\toolbox\matlab\graph3d Elementary 3-D plots Color control and lighting Colormaps Axis control Viewpoint control Camera control Graph notation and printing utility

Graphical user interface tools

C:\MATLAB6p1\toolbox\matlab\uitools GUI functions GUI design tools Dialog boxes Menu utilities Preferences and Miscellaneous utilities Helper and obsolete functions

Version control
C:\MATLAB6p1\toolbox\matlab\verctrl Version control commands Specific version control DemosC:\MATLAB6p1\toolbox\matlab\demos

Symbolic Math Toolbox Control System Toolbox Neural Network Toolbox Instrument Control Toolbox Data Acquisition Toolbox Mapping Toolbox Model Predictive Control Toolbox. Signal Processing Toolbox Partial Differential Equation Toolbox MATLAB Report Generator

Some Toolboxes..

Sparse matrices.
A=[2 3 4;7 0 8;6 0 0] B=sparse(A) Its a different datatype

String functions-Character strings

C:\MATLAB6p1\toolbox\matlab\strfun General String tests String operations Character array name = 'Thomas R. Lee'; title = ' Sr. Developer'; strcat(name,',',title)

Text string
Assign variable to character array S=this is a string Disp(this is a print display) User prompt-input(enter the variable) Error(error message)

MATLAB provides several functions for searching and replacing characters in a string. label = 'Sample 1, 10/28/95'; newlabel = strrep(label,'28','30') position = findstr('amp',label)

String/Numeric Conversion
MATLAB's string/numeric conversion functions change numeric values into character strings. You can store numeric values as digit-by-digit string representations, or convert a value into a hexadecimal or binary string. x=5317 By default, MATLAB stores the number x as a 1by-1 double array containing the value 5317. y = int2str(x); The int2str (integer to string) function breaks this scalar into a 1-by-4 vector containing the string '5317'. p = num2str(pi,9)

Creating Multidimensional Arrays

One way to create a multidimensional array is to create a two-dimensional array and extend it. A = [5 7 8; 0 1 9; 4 3 6]; A(:,:,2) = [1 0 4; 3 5 6; 9 8 7]

Command /function duality

Clear Save junk x y z Whos are commands While Sin(x),Plot(x,y) are functions Both are duals axis off and axis(off)