You are on page 1of 73

MATLAB A brief Introduction !

Shivgan Joshi

www.nanotechbiz.org

Contents
What is MATLAB? Overview Elementary Mathematics Programming I/O M-Files
Basics of M-File Function and Script Files M-File Programming 2D Plots 3D Plots

Graphics

What is MATLAB ?
It stands for MATrix LABoratory

A set of Software comprising


A Very High Level 4th Generation Language Computation Tools Visualization Tools Simulation Tools Integrated Development Environment

MATLABs System
Language: arrays and matrices, control flow, I/O, data structures, user-defined functions and scripts Working Environment: editing, variable management, importing and exporting data, debugging, profiling Graphics system: 2D and 3D data visualization, animation and custom GUI development Mathematical Functions: basic (sum, sin,) to advanced (fft, inv, Bessel functions, ) API: can use MATLAB with C, Fortran, and Java, in either direction

Parts of MATLAB
Developed Environment Programming Language Graphics Toolboxes Application Program Interface

MATLABs Appeal
Interactive code development proceeds incrementally; excellent development and rapid prototyping environment Basic data element is the auto-indexed array This allows quick solutions to problems that can be formulated in vector or matrix form Powerful GUI tools Large collection of toolboxes: collections of topic-related MATLAB functions that extend the core functionality significantly

MATLAB Toolboxes
Math and Analysis
Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition Instrument Control Excel Link Portable Graph Object

Signal & Image Processing


Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design Control System Fuzzy Logic Robust Control -Analysis and Synthesis Model Predictive Control

Data Acquisition and Import

Control Design

MATLABs Important Windows


Command Window: where you enter commands Command History: running history of commands which is preserved across MATLAB sessions Current directory: Default is $matlabroot/work Workspace: GUI for viewing, loading and saving MATLAB variables Array Editor: GUI for viewing and/or modifying contents of MATLAB variables (openvar varname or double-click the arrays name in the Workspace) Editor/Debugger: text editor, debugger; editor works with file types in addition to .m (MATLAB m-files)

MATLABs Main Interface (Desktop)

The MATLABs main interface window called the MATLAB desktop. It consist of Workspace, Command Window, Command History, Current Directory window, and the start button to just get you started.

Editor Window

The Editor Window is used to edit source files and other files such as .m files etc.

MATLABs Help

MATLABs help is very sophisticated. It provides help topics and tutorials on nearly every topic. There is a help for every function available in MATLAB.

Getting Help using Command Window


>> help HELP topics: matlab\general - General purpose commands. matlab\ops - Operators and special characters. matlab\lang - Programming language constructs. matlab\elmat - Elementary matrices and matrix manipulation. matlab\elfun - Elementary math functions. matlab\specfun - Specialized math functions. matlab\matfun - Matrix functions - numerical linear algebra. matlab\datafun - Data analysis and Fourier transforms. matlab\polyfun - Interpolation and polynomials. matlab\funfun - Function functions and ODE solvers. matlab\sparfun - Sparse matrices. matlab\scribe - Annotation and Plot Editing. matlab\graph2d - Two dimensional graphs. matlab\graph3d - Three dimensional graphs. matlab\specgraph - Specialized graphs. matlab\graphics - Handle Graphics. etc...

Command Line Help Topic Help


>> help matfun Matrix functions - numerical linear algebra. Matrix analysis. norm - Matrix or vector norm. normest - Estimate the matrix 2-norm. rank - Matrix rank. det - Determinant. trace - Sum of diagonal elements. null - Null space. orth - Orthogonalization. rref - Reduced row echelon form. subspace - Angle between two subspaces.

Command Line Help Function Help


>> help det DET Determinant. DET(X) is the determinant of the square matrix X. Use COND instead of DET to test for matrix singularity. See also cond. Overloaded functions or methods (ones with the same name in other directories) help laurmat/det.m Reference page in Help browser doc det

Keywords Search in Help Entries


>> lookfor who newton.m: % inputs: 'x' is the number whose square root we seek testNewton.m: % inputs: 'x' is the number whose square root we seek WHO List current variables. WHOS List current variables, long form. TIMESTWO S-function whose output is two times its input. >> whos Name Size Bytes Class Attributes ans 1x1 8 double fid 1x1 8 double i 1x1 8 double

Variables Basics
>> 16 + 24 ans = 40 >> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product product = 8883.8

Variable Basics
>> clear >> product = 2 * 3^3; >> comp_sum = (2 + 3i) + (2 - 3i); >> show_i = i^2; >> save three_things >> clear >> load three_things >> who Your variables are: comp_sum product show_i >> product product = 54 >> show_i show_i = -1

MATLAB Data Types Basics


The basic data type used in MATLAB is the double precision array

No declarations needed: MATLAB automatically allocates required memory


Resize arrays dynamically

To reuse a variable name, simply use it in the left hand side of an assignment statement
MATLAB displays results in scientific notation
Use File/Preferences and/or format function to change default short (5 digits), long (16 digits)

Variables Basics
Variable names are case sensitive and over-written when re-used Basic variable class: Auto-Indexed Array Allows use of entire arrays (scalar, 1-D, 2-D, etc) as operands Vectorization: Always use array operands to get best performance (see next slide) Terminology: scalar (1 x 1 array), vector (1 x N array), matrix (M x N array) Special variables/functions: ans, pi, eps, inf, NaN, i, nargin, nargout, varargin, varargout, ... Commands who (terse output) and whos (verbose output) show variables in Workspace

Multi-Dimensional Arrays
>> r = randn(2,3,4) % create a 3 dimensional array filled with normally distributed random numbers r(:,:,1) = -0.6918 1.2540 -1.4410 0.8580 -1.5937 0.5711 r(:,:,2) = -0.3999 0.8156 1.2902 0.6900 0.7119 0.6686 r(:,:,3) = 1.1908 -0.0198 -1.6041 -1.2025 -0.1567 0.2573 r(:,:,4) = -1.0565 -0.8051 0.2193 1.4151 0.5287 -0.9219

Strings
>> hi = ' hello'; >> class = 'MATLAB'; >> hi hi = hello >> class class = MATLAB >> greetings = [hi class] greetings = helloMATLAB >> vgreetings = [hi;class] vgreetings = hello MATLAB

Diagonal Elements of Matrix


>> durer durer = 16 3 5 10 9 6 4 15 2 13 11 8 7 12 14 1

>> diag(durer) % diag plucks out the diagonal elements ans = 16 10 7 1 >> sum(diag(durer)) ans = 34

Other Diagonal using Flip Left-Right


>> durer durer = 16 3 5 10 9 6 4 15 2 13 11 8 7 12 14 1

>> fliplr(durer) % flip left-right ans = 13 2 3 16 8 11 10 5 12 7 6 9 1 14 15 4 >> sum(diag(fliplr(durer))) ans = 34

Accessing Elements using Sub-Scripting


>> durer durer = 16 3 5 10 9 6 4 15 2 13 11 8 7 12 14 1

>> diag_sum = durer(1,1) + durer(2,2) + durer(3,3) diag_sum = 33 >> durer(4,4) = pi durer = 16.0000 3.0000 2.0000 13.0000 5.0000 10.0000 11.0000 8.0000 9.0000 6.0000 7.0000 12.0000 4.0000 15.0000 14.0000 3.1416

The colon operator


>> 1:5 % use the colon operator to create row vectors ans = 1 2 3 4 5 >> 1:0.9:6 % you can vary the increment (0.9 in this case) ans = 1.0000 1.9000 2.8000 3.7000 4.6000 5.5000

The last element is always less than or equal to the upper limit

Scripts and Functions


Scripts do not accept input arguments, nor do they produce output arguments. Scripts are simply MATLAB commands written into a file. They operate on the existing workspace. Functions accept input arguments and produce output variables. All internal variables are local to the function and commands operate on the function workspace. A file containing a script or function is called an m-file If duplicate functions (names) exist, the first in the search path (from path command) is executed.

Function - Example
function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; >> myfun(2,3) % called with zero outputs ans = 100 >> u = myfun(2,3) % called with one output u= 100 >> [u v w] = myfun(2,3) % called with all outputs u= 100 v= 6 w= 4

Syntax of Function
If the m-file name and function name differ, the file name takes precedence Function names must begin with a letter First line must contain function followed by the most general calling syntax Statements after initial contiguous comments (help lines) are the body of the function

Terminates on the last line or a return statement

If-Else Statement
>> A = 2; B = 3; >> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') end ans = B is bigger

Switch Statement
>> n = 8 n= 8 >> switch(rem(n,3)) case 0 m = 'no remainder' case 1 m = the remainder is one' case 2 m = the remainder is two' otherwise error('not possible') end m= the remainder is two

For Loop
>> for i = 2:5 for j = 3:6 a(i,j) = (i + j)^2 end end >> a a= 0 0 0 0 0 0 0 0 25 36 49 64 0 0 36 49 64 81 0 0 49 64 81 100 0 0 64 81 100 121

While Loop
>> b = 4; a = 2.1; count = 0; >> while b - a > 0.01 a = a + 0.001; count = count + 1; end >> count count = 1891

Loading and Saving Workspace


MATLAB can load and save data in .MAT format .MAT files are binary files that can be transferred across platforms; as much accuracy as possible is preserved. Load: load filename OR A = load(filename)
loads all the variables in the specified file (the default name is MATLAB.MAT)

Save: save filename variables


saves the specified variables (all variables by default) in the specified file (the default name is MATLAB.MAT)

Low-Level File I/O


File Opening and Closing
fclose: Close one or more open files fopen: Open a file or obtain information about open files fread: Read binary data from file fwrite: Write binary data to a file fgetl: Return the next line of a file as a string without line terminator(s) fgets: Return the next line of a file as a string with line terminator(s) fprintf: Write formatted data to file fscanf: Read formatted data from file

Unformatted I/O

Formatted I/O

Low-Level File I/O


File Positioning
feof: Test for end-of-file ferror: Query MATLAB about errors in file input or output frewind: Rewind an open file fseek: Set file position indicator ftell: Get file position indicator

String Conversion
sprintf: Write formatted data to a string sscanf: Read string under format control

Example
fid = fopen(filename, permission);

status = fclose(fid);
fscanf: [A, count] = fscanf(fid,format,size); fprintf: count = fprintf(fid, format, A,...); fscanf and fprintf are similar to C version but vectorized

Format Specifiers
Specifier Description %c Single character %d Decimal notation (signed) %e Exponential notation %f Fixed-point notation %g The more compact of %e or %f %o Octal notation (unsigned) %s String of characters %u Decimal notation (unsigned) %x Hexadecimal notation etc.

Other I/O Commands


fgetl: line = fgetl(fid);
reads next line from file without line terminator reads next line from file with line terminator reads N lines of formatted text from file filename reads string under format control

fgets: line = fgets(fid);

textread: [A,B,C,...] = textread('filename','format',N) sscanf: A = sscanf(s, format, size); sprintf: s = sprintf(format, A);

writes formatted data to a string

Read and Write


[data, count] = fread(fid, num, precision);

count = fwrite(fid, data, precision);

fread and fwrite are vectorized

File Pointer Commands


feof: tf = feof(fid);
tests for end of file sets the file position

fseek: status = fseek(fid, offset, origin);


ftell: position = ftell(fid);
gets the file position rewinds the file

frewind: frewind(fid); ferror: message = ferror(fid);


inquire about file I/O status

Structures
Multidimensional MATLAB arrays Access elements using textual field designators Create structures by using periods (.):
>> class.name = MATLAB; >> class.day1 = 2/27/07; >> class.day2 = 2/28/07; >> class class = name: MATLAB day1: 2/27/07 day2: 2/28/07

Using Structures
Structures are like arrays Fields can be added one at a time:
>> class(2).name = MPI; >> class(2).day1 = TBA; >> class(2).day2 = TBA;

Can also use a single statement:


>> class(2) = struct(name,MPI,... day1,TBA,day2,TBA)

Using Structures
Consider the simple structure
>> exam.name = Jim Kirk; >> exam.score = 79; >> exam(2).name = Janice Lester; >> exam(2).score = 89; >> [exam.score] ans = 79 89

Using Structures
Can also create a cell array using curly braces:
>> {exam.name} ans = 'Jim Kirk' 'Janice Lester'

The MAX and MIN functions


[Y,I] = MAX(X) returns the indices of the maximum values in vector I. If the values along the first non-singleton dimension contain more than one maximal element, the index of the first one is returned.
>> max(rpm_raw) ans = 1115 1120 1043 >> max(max(rpm_raw)) ans = 1120 >> [y,i] = max(rpm_raw) y= 1115 1120 1043 i= 8 2 17

MIN Function
>> min(rpm_raw) ans = 1053 1053 961

>> min(min(rpm_raw)) ans = 961

>> [y,i] = min(rpm_raw) y= 1053 1053 961 i= 22 1 22

Median, Covariance and Standard Deviation


The median is used to calculate median, cov for covariance, std for standard deviation, var for variance
>> median(rpm_raw) % median along each column ans = 1080 1083.5 1004 >> cov(rpm_raw) % covariance of the data ans = 306.4 -34.76 32.192 -34.76 244.9 -165.21 32.192 -165.21 356.25 >> std(rpm_raw) % standard deviation along each column ans = 17.504 15.649 18.875 >> var(rpm_raw) % variance is the square of std ans = 306.4 244.9 356.25

Polynomial Equation
The equation in MATLAB is represented as
>> p = [1 -6 -72 -27] p= 1 -6 -72 -27 >> roots(p) ans = 12.1229 -5.7345 -0.3884

Using Symbolic Computation Toolbox


syms or sym is used to declare symbols
>> syms x y >> y = x^4 + x^2 + (x*2) + 87 y= x^4 + x^2 + 2*x + 87

>> subs(y, x, 10) ans = 10207

Differentiation and Integration


The diff and int functions are used to differentiate and integrate respectively
>> syms x y >> y = x^2 + x + 1 y= x^2 + x + 1
>> differentiation = diff(y, x) differentiation = 2*x + 1 >> integration = int(y, x) integration = (x*(2*x^2 + 3*x + 6))/6

A simple Plot

>> x = [0:pi/100:pi]; >> y = sin(x); >> plot(x,y), title('Simple Plot')

Multiple Plots

>> z = cos(x); >> plot(x,y,'g.',x,z,'b-.'), title('More Complicated')

Contour and Mesh

>> t = 0:pi/25:pi; >> [x,y,z] = cylinder(4*cos(t)); >> subplot(2,1,1) >> contour(y) >> subplot(2,1,2) >> mesh(x,y,z) >> xlabel('x') >> ylabel('this is the y axis') >> text(1,-2,0.5,... '\it{Note the gap!}')

Used to display multiple plots in the same figure window subplot(m,n,i) subdivides the window into m-by-n subregions (subplots) and makes the ith subplot active for the current plot
>> subplot(2,3,1) >> plot(t, sin(t), 'r:square') >> axis([-Inf,Inf,-Inf,Inf]) >> subplot(2,3,3) >> plot(t, cos(t), 'g') >> axis([-Inf,Inf,-1,1])

Subplots

>> subplot(2,3,5) >> plot(t, sin(t).*cos(t), 'b-.') >> axis([-Inf,Inf,-Inf,Inf])

Mesh Plot

mesh(Z) generates a wireframe view of matrix Z, where Z(i,j) define the height of a surface over the rectangular x-y grid
>> figure(2); >> [X,Y] = meshgrid(16:1.0:16); >> Z = sqrt(X.^2 + Y.^2 + 5000); >> mesh(Z)

Surface Plots

surf(Z) generates a colored faceted 3-D view of the surface. By default, the faces are quadrilaterals, each of constant color, with black mesh lines The shading command allows you to control the view
>> figure(2); >> [X,Y] = meshgrid(16:1.0:16); >> Z = sqrt(X.^2 + Y.^2 + 5000); >> surf(Z)

Flat Shading

>> shading flat

Interpolated Shading

>> shading interp

>> colormap hot

>> colormap gray

>> colormap cool

>> colormap pink

Contour Plot

Use to create, display, and label isolines determined by one or more matrices contour(Z) generates isolines from values given by a matrix Z and displays it in 2-D

Contour Plot

Use to create, display, and label isolines determined by one or more matrices contour3(Z) generates isolines from values given by a matrix Z and displays it in 3-D

Reading Images
MATLAB can read images of various formats including BMP, HDF, JPEG, PCX, TIFF, XWD Use function imread to read image files imread reads indexed, intensity, and truecolor images Images are read into a uint8 matrix of appropriate size imread automatically determines the format of the image based on information in the header You can specify a format as an optional second argument

Reading Image - Example


>> Crusader = imread(Crusader.jpg'); >> image(Crusader) >> whos Crusader Name Size Bytes Class Crusader 186x250x3 139500 uint8 array Grand total is 139500 elements using 139500 bytes

Writing Images
MATLAB can write images of various formats including the following BMP, HDF, JPEG, PCX, TIFF, XWD Use function imwrite to write image files imwrite writes indexed, intensity, and truecolor images Images are written as a uint8 matrix (converted if necessary) of appropriate size along with colormaps (if necessary) and headers imwrite determines the format from extension of filename. You can specify an optional format if extension is absent or to force a particular format

Writing Images - Example


>> Abrams = imread(Abrams.jpg'); >> image(Abrams) >> whos Abrams Name Size Bytes Class Abrams 511x640x3 981120 uint8 array Grand total is 981120 elements using 981120 bytes >> % Write out tank as gray image >> AbramsGray = rgb2gray(Abrams); >> colormap gray; >> image(AbramsGray) >> imwrite(AbramsGray, gray, 'Abrams.bmp');

MEX Basics
MEX stands for MATLAB EXecutable MEX files are C and FORTRAN programs that are callable from MATLAB after compiling Why?
Pre-existing C/FORTRAN programs can be called from MATLAB without rewriting codes in MATLAB Computations that do not run fast enough in MATLAB, such as for loops, can be coded in C or FORTRAN for efficient implementation. Access to hardware such as A/D, D/A converters, GPIB hardware, serial/parallel port, etc.

Using MEX
1. Prepare the C or Fortran MEX program according to MATLAB external interfacing rules 2. Compile the C or FORTRAN MEX program using MATLAB command mex 3. mex in turn makes use of external C or FORTRAN compilers 4. Call the compiled MEX function in the same way as calling any MATLAB function

Changing MATLABs Startup behavior


Customize MATLABs start-up behavior Create startup.m file and place in: $matlabroot\work My startup.m file:
addpath e:\download\MatlabMPI\src addpath e:\download\MatlabMPI\examples addpath .\MatMPI format short g format compact

MATLABs path
The addpath command adds directories to the MATLAB search path. The specified directories are added to the beginning of the search path. rmpath is used to remove paths from the search path
>> addpath('c:\'); >> matlabpath

c:\ E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\toolbox\matlab\ops

MATLABPATH

Some common commands


ls / dir provide a directory listing of the current directory
>> ls . .. >>
sample.m

pwd shows the current directory


>> pwd ans = e:\Program Files\MATLAB\R2006b\work >>

Some common commands


The system command can be used to run OS commands On Unix systems, the unix command can be used as well On DOS systems, the corresponding command is dos
>> dos('date') The current date is: Thu 01/04/2007 Enter the new date: (mm-dd-yy) ans = 0

Links of Online MATLAB Resources


www.mathworks.com/ www.mathtools.net/MATLAB www.math.utah.edu/lab/ms/matlab/matlab.html web.mit.edu/afs/athena.mit.edu/software/matlab/ www/home.html www.utexas.edu/its/rc/tutorials/matlab/ www.math.ufl.edu/help/matlab-tutorial/ www.indiana.edu/~statmath/math/matlab/links.ht ml wwwh.eng.cam.ac.uk/help/tpl/programs/matlab.html

Thanking You
Shivgan Joshi

www.nanotechbiz.org

You might also like