Professional Documents
Culture Documents
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
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 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
Control Design
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.
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
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
>> diag(durer) % diag plucks out the diagonal elements ans = 16 10 7 1 >> sum(diag(durer)) ans = 34
>> 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 last element is always less than or equal to the upper limit
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
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
Unformatted I/O
Formatted I/O
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.
textread: [A,B,C,...] = textread('filename','format',N) sscanf: A = sscanf(s, format, size); sprintf: s = sprintf(format, A);
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;
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'
MIN Function
>> min(rpm_raw) ans = 1053 1053 961
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
A simple Plot
Multiple Plots
>> 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
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
Interpolated Shading
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
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
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
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
MATLABPATH
Thanking You
Shivgan Joshi
www.nanotechbiz.org