MATLAB Quick Reference: General Purpose Commands
MATLAB Quick Reference: General Purpose Commands
MATLAB Quick Reference: General Purpose Commands
clear disp length load memory mlock munlock openvar pack save saveas size who, whos workspace
Remove items from the workspace Display text or array Length of vector Retrieve variables from disk Help for memory limitations Prevent M-file clearing Allow M-file clearing Open workspace variable in Array Editor, for graphical editing Consolidate workspace memory Save workspace variables on disk Save figure or model using specified format Array dimensions List the variables in the workspace Display the Workspace Browser, a GUI for managing the workspace
fullfile info inmem ls matlabroot mkdir open pwd tempdir tempname unix !
Build full filename from parts Display contact information or toolbox Readme files Functions in memory List directory on UNIX Get root directory of MATLAB installation Make new directory Open files based on extension Display current directory Return the name of the systems temporary directory Unique name for temporary file Execute a UNIX command and return the result Execute operating system command
Comma Semicolon Comment Exclamation point Transpose and quote Nonconjugated transpose Assignment Equality Relational operators Logical and Logical or Logical not Logical exclusive or
cos, cosh cot, coth csc, csch exp fix floor gcd imag lcm log log2 log10 mod nchoosek real rem round sec, sech sign sin, sinh sqrt tan, tanh
Cosine and hyperbolic cosine Cotangent and hyperbolic cotangent Cosecant and hyperbolic cosecant Exponential Round towards zero Round towards minus infinity Greatest common divisor Imaginary part of a complex number Least common multiple Natural logarithm Base 2 logarithm and dissect floating-point numbers into exponent and mantissa Common (base 10) logarithm Modulus (signed remainder after division) Binomial coefficient or all combinations Real part of complex number Remainder after division Round to nearest integer Secant and hyperbolic secant Signum function Sine and hyperbolic sine Square root Tangent and hyperbolic tangent
case catch continue else elseif end error for if otherwise return switch try warning while
Case switch Begin catch block Pass control to the next iteration of for or while loop Conditionally execute statements Conditionally execute statements Terminate for, while, switch, try, and if statements or indicate last index Display error messages Repeat statements a specific number of times Conditionally execute statements Default part of switch statement Return to the invoking function Switch among several cases based on expression Begin try block Display warning message Repeat statements an indefinite number of times
Logical Functions
all any exist find is* isa iskeyword isvarname logical mislocked Test to determine if all elements are nonzero Test for any nonzeros Check if a variable or file exists Find indices and values of nonzero elements Detect state Detect an object of a given class Test if string is a MATLAB keyword Test if string is a valid variable name Convert numeric values to logical True if M-file cannot be cleared
Interactive Input
input keyboard menu pause Request user input Invoke the keyboard in an M-file Generate a menu of choices for user input Halt execution temporarily
Object-Oriented Programming
class double inferiorto inline int8, int16, int32 isa loadobj saveobj single superiorto Create object or return class of object Convert to double precision Inferior class relationship Construct an inline object Convert to signed integer Detect an object of a given class Extends the load function for user objects Save filter for objects Convert to single precision Superior class relationship
Control Flow
break Terminate execution of for loop or while loop
Debugging
dbclear Clear breakpoints
dbcont dbdown dbmex dbquit dbstack dbstatus dbstep dbstop dbtype dbup
Resume execution Change local workspace context Enable MEX-file debugging Quit debug mode Display function call stack List all breakpoints Execute one or more lines from a breakpoint Set breakpoints in an M-file function List M-file with line numbers Change local workspace context
Compare the first n characters of strings Compare the first n characters of strings, ignoring case String search and replace First token in string Vertical concatenation of strings Determine symbolic variables in an expression Produce the TeX format from a character string Convert string to upper case
: (colon)
Function Handles
function_ha MATLAB data type that is a handle to a function ndle functions func2str str2func Return information about a function handle Constructs a function name string from a function handle Constructs a function handle from a function name string
Radix Conversion
bin2dec dec2bin dec2hex hex2dec Binary to decimal number conversion Decimal to binary number conversion Decimal to hexadecimal number conversion Hexadecimal to decimal number conversion Hexadecimal to double number conversion
hex2num
String Manipulation
deblank findstr lower strcat strcmp strcmpi strjust strmatch Strip trailing blanks from the end of a string Find one string within another Convert string to lower case String concatenation Compare strings Compare strings, ignoring case Justify a character array Find possible matches for a string
Matrix Manipulation
cat diag fliplr flipud Concatenate arrays Diagonal matrices and diagonals of a matrix Flip matrices left-right Flip matrices up -down
Replicate and tile an array Reshape array Rotate matrix 90 degrees Lower triangular part of a matrix Upper triangular part of a matrix Index into array, rearrange array
Structure Functions
fieldnames getfield rmfield setfield struct struct2cell Field names of a structure Get field of structure array Remove structure fields Set field of structure array Create structure array Structure to cell array conversion
sub2ind
Vector Functions
cross dot intersect ismember setdiff setxor union unique Vector cross product Vector dot product Set intersection of two vectors Detect members of a set Return the set difference of two vector Set exclusive or of two vectors Set union of two vectors Unique elements of a vector
Specialized Matrices
compan gallery hadamard hankel hilb invhilb magic pascal toeplitz wilkinson Companion matrix Test matrices Hadamard matrix Hankel matrix Hilbert matrix Inverse of the Hilbert matrix Magic square Pascal matrix Toeplitz matrix Wilkinsons eigenvalue test matrix
Bitwise Functions
bitand bitcmp bitor bitmax bitset bitshift bitget bitxor Bit-wise AND Complement bits Bit-wise OR Maximum floating-point integer Set bit Bit-wise shift Get bit Bit-wise XOR
Formatted I/O
fgetl fgets Return the next line of a file as a string without line terminator(s) 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
File Positioning
feof Test for end-of-file
Query MATLAB about errors in file input or output Set file position indicator Get file position indicator
rat, rats
Hessenberg form of a matrix Polynomial with specified roots QZ factorization for generalized eigenvalues Convert real Schur form to complex Schur form Schur decomposition Singular value decomposition
String Conversion
sprintf sscanf Write formatted data to a string Read string under format control
Matrix Functions
expm funm logm sqrtm Matrix exponential Evaluate general matrix function Matrix logarithm Matrix square root
textread Read formatted data from text file wk1read Read a Lotus123 WK1 spreadsheet file into a matrix wk1writ Write a matrix to a Lotus123 WK1 spreadsheet file e
Linear Equations
chol inv lscov lu lsqnonneg minres pinv qr symmlq Cholesky factorization Matrix inverse Least squares solution in the presence of known covariance LU matrix factorization Nonnegative least squares Minimum Residual Method Moore-Penrose pseudoinverse of a matrix Orthogonal-triangular decomposition Symmetric LQ method
gamma, gammainc, Gamma functions gammaln legendre pow2 Associated Legendre functions Base 2 power and scale floating-point numbers
var
Variance
Polynomial with specified roots Polynomial derivative Polynomial eigenvalue problem Polynomial curve fitting Analytic polynomial integration Polynomial evaluation Convert between partial fraction expansion and polynomial coefficients Polynomial roots
Finite Differences
del2 diff Discrete Laplacian Differences and approximate derivatives
Correlation
corrcoef cov Correlation coefficients Covariance matrix
roots
Fourier Transforms
abs angle cplxpair fft fft2 fftshift ifft ifft2 ifftn ifftshift unwrap Absolute value and complex magnitude Phase angle Sort complex numbers into complex conjugate pairs One-dimensional fast Fourier transform Two-dimensional fast Fourier transform Shift DC component of fast Fourier transform to center of spectrum Inverse one-dimensional fast Fourier transform Inverse two-dimensional fast Fourier transform Inverse multidimensional fast Fourier transform Inverse FFT shift Correct phase angles
meshgrid Generate X and Y matrices for three-dimensional plots ndgrid pchip ppval spline tsearch tsearchn voronoi voronoin
spconvert
Incomplete LU matrix factorizations Preconditioned Conjugate Gradients method Quasi-Minimal Residual method Orthogonal-triangular decomposition Delete column from QR factorization Insert column in QR factorization Rank 1 update to QR factorization
Volumetric slice plot Generate sphere Plot discrete surface data Waterfall plot
Three-Dimensional Plotting
bar3 bar3h comet3 cylinder fill3 plot3 quiver3 Vertical 3-D bar chart Horizontal 3-D bar chart 3-D comet plot Generate cylinder Draw filled 3-D polygons in 3-space Plot lines and points in 3-D space 3-D quiver (or velocity) plot
Volume Visualization
coneplot contourslice curl divergence Plot velocity vectors as cones in 3-D vector field Draw contours in volume slice plane Compute the curl and angular velocity of a vector field Compute the divergence of a vector field
flow interpstreamspeed isocaps isocolors isonormals isosurface reducepatch reducevolume shrinkfaces slice smooth3 stream2 stream3 streamline streamparticles streamribbon streamslice streamtube surf2patch subvolume volumebounds
Generate scalar volume data Interpolate streamline vertices from vector-field magnitudes Compute isosurface end-cap geometry Compute the colors of isosurface vertices Compute normals of isosurface vertices Extract isosurface data from volume data Reduce the number of patch faces Reduce number of elements in volume data set Reduce the size of patch faces Draw slice planes in volume Smooth 3-D data Compute 2-D stream line data Compute 3-D stream line data Draw stream lines from 2- or 3-D vector data Draws stream particles from vector volume data Draws stream ribbons from vector volume data Draws well-spaced stream lines from vector volume data Draws stream tubes from vector volume data Convert srface data to patch data Extract subset of volume data set Return coordinate and color limits for volume (scalar and vector)
ezplot3 ezpolar ezsurf ezsurfc feather fill fplot pareto pie3 plotmatrix pcolor rose quiver ribbon stairs scatter scatter3 stem convhull delaunay dsearch inpolygon polyarea tsearch voronoi
Easy to use 3-D parametric curve plotter Easy to use polar coordinate plotter Easy to use 3-D colored surface plotter Easy to use combination surface/contour plotter Feather plot Draw filled 2-D polygons Plot a function Pareto char 3-D pie plot Scatter plot matrix Pseudocolor (checkerboard) plot Plot rose or angle histogram Quiver (or velocity) plot Ribbon plot Stairstep graph Scatter plot 3-D scatter plot Plot discrete sequence data Convex hull Delaunay triangulation Search Delaunay triangulation for nearest point True for points inside a polygonal region Area of polygon Search for enclosing Delaunay triangle Voronoi diagram
Set or get plot box aspect ratio 3-D graph viewpoint specification. Generate view transformation matrices Set or get the current x-axis limits Set or get the current y-axis limits Set or get the current z-axis limits
Lighting
camlight light lighting lightangle material Cerate or position Light Light object creation function Lighting mode Position light in sphereical coordinates Material reflectance mode
Transparency
alpha alphamap alim Set or query transparency properties for objects in current axes Specify the figure alphamap Set or query the axes alpha limits
Color Operations
brighten caxis colorbar colordef Brighten or darken color map Pseudocolor axis scaling Display color bar (color scale) Set up color defaults Set the color look-up table (list of colormaps) Graphics figure defaults set for grayscale monitor Hue-saturation-value to red-green-blue conversion RGB to HSVconversion Plot color map Color shading mode Spin the colormap 3-D surface normals Change axes background color for plots
Domain Generation
griddata meshgrid Data gridding and surface fitting Generation of X and Y arrays for 3-D plots
View Control
camdolly Move camera position and target View specific objects Orbit about camera target Rotate camera target about camera position Set or get camera position Set or get projection type Rotate camera about viewing axis Set or get camera target Set or get camera up-vector Set or get camera view angle Zoom camera in or out Set or get data aspect ratio camlookat camorbit campan campos camproj camroll camtarget camup camva camzoom daspect
Specialized Plotting
area box comet compass errorbar ezcontour ezcontourf ezmesh ezmeshc ezplot Area plot Axis box for 2-D and 3-D plots Comet plot Compass plot Plot graph with error bars Easy to use contour plotter Easy to use filled contour plotter Easy to use 3-D mesh plotter Easy to use combination mesh/contour plotter Easy to use function plotter
Colormaps
autumn bone Shades of red and yellow color map Gray-scale with a tinge of blue color map
contrast cool copper flag gray hot hsv jet lines prism spring summer winter
Gray color map to enhance image contrast Shades of cyan and magenta color map Linear copper-tone color map Alternating red, white, blue, and black color map Linear gray-scale color map Black-red-yellow-white color map Hue-saturation-value (HSV) color map Variant of HSV Line color colormap Colormap of prism colors Shades of magenta and yellow color map Shades of green and yellow colormap Shades of blue and green color map
setappdata
Region of Interest
dragrect drawnow rbbox Drag XOR rectangles with mouse Complete any pending drawing Rubberband box
Printing
orient pagesetupdlg print printdlg printopt saveas Hardcopy paper orientation Page position dialog box Print graph or save graph to file Print dialog box Configure local printer defaults Save figure to graphic file
helpdlg inputdlg listdlg msgbox pagedlg printdlg questdlg uigetfile uiputfile uisetcolor uisetfont warndlg
Object Manipulation
reset rotate3d Reset axis or figure Interactively rotate the view of a 3-D plot
mexWarnMsgTxt
Get cell's contents Get mxArray's class Get mxArray's class Get pointer to data Get pointer to dimensions array Get number of bytes required to store each data element Get value of eps Get field value, given field name and index in structure array Get field value, given field number and index in structure array
C MX Functions
mxAddField mxArrayToString mxAssert mxAssertS mxCalcSingleSubscript mxCalloc mxChar mxClassID mxClearLogical mxComplexity mxCreateCellArray mxCreateCellMatrix mxCreateCharArray Add field to structure array Convert arrays to strings Check assertion value Check assertion value; doesn't print assertion's text Return offset from first element to desired element Allocate dynamic memory String mxArrays data type Enumerated data type that identifies mxArray's class Clear logical flag Specifies if mxArray has imaginary components Create unpopulated N-dimensional cell mxArray Create unpopulated two-dimensional cell mxArray Create unpopulated N-dimensional string mxArray
mxGetFieldNameByNum Get field name, given field number in structure array ber mxGetFieldNumber mxGetImagData mxGetInf mxGetIr mxGetJc mxGetM mxGetN mxGetName mxGetNaN Get field number, given field name in structure array Get pointer to imaginary data of mxArray Get value of infinity Get ir array of sparse matrix Get jc array of sparse matrix Get number of rows Get number of columns or number of elements Get name of specified mxArray Get the value of NaN
mxCreateCharMatrixFr Create populated t wo-dimensional string mxArray omStrings mxCreateDoubleMatrix Create unpopulated two-dimensional, doubleprecision, floating-point mxArray
mxGetNumberOfDimens Get number of dimensions ions mxGetNumbe rOfElemen Get number of elements in array ts mxGetNumberOfFields mxGetNzmax mxGetPi mxGetPr mxGetScalar mxGetString mxIsCell mxIsChar mxIsClass mxIsComplex mxIsDouble Get number of fields in structure mxArray Get number of elements in ir, pr, and pi arrays Get mxArray's imaginary data elements Get mxArray's real data elements Get real component of mxArray's first data element Copy string mxArray's data into C-style string True if cell mxArray True if string mxArray True if mxArray is member of specified class True if data is complex True if mxArray represents its data as doubleprecision, floating-point numbers
mxCreateNumericArray Create unpopulated N-dimensional numeric mxArray mxCreateNumericMatrix Create numeric matrix and initialize data elements to 0 mxCreateScalarDouble mxCreateSparse mxCreateString mxCreateStructArray mxCreateStructMatrix mxDestroyArray mxDuplicateArray mxFree Create scalar, double-precision array initialized to specified value Create two-dimensional unpopulated sparse mxArray Create 1-by-n string mxArray initialized to specified strin g Create unpopulated N-dimensional structure mxArray Create unpopulated two-dimensional structure mxArray Free dynamic memory allocated by an mxCreate routine Make deep copy of array Free dynamic memory allocated by mxCalloc
mexMakeArrayPersisten Make mxArray persist after MEX-file completes t mexMakeMemoryPersist Make memory allocated by MATLAB's memory allocation routines persist after ent MEX-file completes mexPrintf mexPutArray mexSet mexSetTrapFlag mexUnlock ANSI C printf-style output routine Copy mxArray from your MEX-file into another workspace Set value of Handle Graphics property Control response of mexCallMATLAB to errors Unlock MEX-file so it can be cleared from memory
mxIsEmpty mxIsFinite mxIsFromGlobalWS mxIsInf mxIsInt8 mxIsInt16 mxIsInt32 mxIsLogical mxIsNaN mxIsNumeric mxIsSingle mxIsSparse mxIsStruct mxIsUint8 mxIsUint16 mxIsUint32 mxMalloc mxRealloc mxRemoveField mxSetAllocFcns
True if mxArray is empty True if value is finite True if mxArray was copied from MATLAB's global workspace True if value is infinite True if mxArray represents its data as signed 8-bit integers True if mxArray represents its data as signed 16-bit integers True if mxArray represents its data as signed 32-bit integers True if mxArray is Boolean True if value is NaN True if mxArray is numeric True if mxArray represents its data as singleprecision, floating-point numbers True if sparse mxArray True if structure mxArray True if mxArray represents its data as unsigned 8-bit integers True if mxArray represents its data as unsigned 16-bit integers True if mxArray represents its data as unsigned 32-bit integers Allocate dynamic memory using MATLAB's memory manager Reallocate memory Remove field from structure array Register memory allocation/deallocation functions in stand-alone engine or MAT application Set value of one cell Convert MATLAB structure array to MATLAB object array Set pointer to data Modify number/size of dimensions Set field value of structure array, given field name/index Set field value in structure array, given field number/index Set imaginary data pointer for mxArray Set ir array of sparse mxArray Set jc array of sparse mxArray Set logical flag Set number of rows
Set number of columns Set name of mxArray Set storage space for nonzero elements Set new imaginary data for mxArray Set new real data for mxArray
Read binary data from the device Read data from the device, and format as text Write binary data to the device Stop asynchronous read and write operations
C Engine Routines
engClose engEvalString engGetArray engOpen engOpenSingleUse engOutputBuffer engPutArray Quit engine session Evaluate expression in string Copy variable from engine workspace Start engine session Start engine session for single, nonshared use Specify buffer for MATLAB output Put variables into engine workspace
State Change
fclose fopen record Disconnect a serial port object from the device Connect a serial port object to the device Record data and event information to a file
C MAT-File Routines
matClose matDeleteArray matGetArray matGetArrayHeader matGetDir matGetFp matGetNextArray matGetNextArrayHeader matOpen matPutArray matPutArrayAsGlobal Close MAT-file Delete named mxArray from MAT -file Read mxArray from MAT-file Load header array information only Get directory of mxArrays in MAT-file Get file pointer to MAT-file Read next mxArray from MAT -file Load array header information only Open MAT-file Write mxArrays into MAT-files Put mxArrays into MAT-files
General Purpose
clear delete disp Remove a serial port object from the MATLAB workspace Remove a serial port object from memory Display serial port object summary information Return serial port objects from memory to the MATLAB workspace Determine if serial port objects are valid Length of serial port object array Load serial port objects and variables into the MATLAB workspace Save serial port objects and variables to a MAT-file Size of serial port object array
instraction Display event information when an event occurs instrfind isvalid length load save size
mxSetCell mxSetClassName mxSetData mxSetDimensions mxSetField mxSetFieldByNumber mxSetImagData mxSetIr mxSetJc mxSetLogical mxSetM
Figure
AlphaMap; BackingStore; BusyAction; ButtonDownFcn; Children; Clipping; CloseRequestFcn; Color; Colormap; CreateFcn; CurrentAxes; CurrentCharacter; CurrentObject; CurrentPoint; DeleteFcn; Dithermap; DithermapMode; DoubleBuffer; FixedColors; HandleVisibility; HitTest; IntegerHandle; Interruptible; InvertHardcopy; KeyPressFcn; MenuBar; MinColormap; Name; NextPlot; NumberTitle; PaperOrientation; PaperPosition; PaperPositionMode; PaperSize; PaperType; PaperUnits; Parent; Pointer; PointerShapeCData; PointerShapeHotSpot; Position; Renderer; RendererMode; Resize; ResizeFcn; Selected; SelectionHighlight; SelectionType; ShareColors; Tag; Type; UIContextMenu; Units; UserData; Visible; WindowButtonDownFcn; WindowButtonMotionFcn; WindowButtonUpFcn; WindowStyle
BackgroundColor; BusyAction; ButtonDownFcn; Callback; CData; Children; Clipping; CreateFcn; DeleteFcn; Enable; Extent; FontAngle; FontName; FontSize; FontUnits; FontWeight; ForegroundColor; HandleVisibility; HitTest; HorizontalAlignment; Interruptible; ListboxTop; Max; Min; Parent; Position; Selected; SelectionHighlight; SliderStep; String; Style; Tag; TooltipString; Type; UIContextMenu; Units; UserData; Value; Visible
Uimenu
Accelerator; BusyAction; ButtonDownFcn; Callback; Checked; Children; Clipping; CreateFcn; DeleteFcn; Enable; ForegroundColor; HandleVisibility; HitTest; Interruptible; Label; Parent; Position; Selected; SelectionHighlight; Separator; Tag; Type; UIContextMenu; UserData; Visible
Axes
ALim; ALimMode; AmbientLightColor; Box; BusyAction; ButtonDownFcn; CLim; CLimMode; CameraPosition; CameraPositionMode; CameraTarget; CameraTargetMode; CameraUpVector; CameraUpVectorMo de; CameraViewAngle; CameraViewAngleMode; Children; Clipping; Color; ColorOrder; CreateFcn; CurrentPoint; DataAspectRatio; DataAspectRatioMode; DeleteFcn; DrawMode; FontAngle; FontName; FontSize; FontUnits; FontWeight; GridLineStyle; HandleVisibility; HitTest; Interruptible; Layer; LineStyleOrder; LineWidth; NextPlot; Parent; PlotBoxAspectRatio; PlotBoxAspectRatioMode; Position; Projection; Selected; SelectionHighlight; Tag; TickDir; TickDirMode; TickLength; Title; Type; Units; UIContextMenu; UserData; View; Visible; XAxisLocation; XColor; Xdir; XGrid; XLabel; XLim; XLimMode; XScale; XTick; XTickLabel; XTickLabelMode; XTickMode; YAxisLocation; YColor; YDir; YGrid; YLabel; YLim; YLimMode; YScale; YTick; YTickLabel; YTickLabelMode; YTickMode; ZColor; ZDir; ZGrid; ZLabel; ZLim; ZLimMode; ZScale; ZTick; ZTickLabel; ZTickLabelMode; ZtickMode
Line
BusyAction; ButtonDownFcn; Children; Clipping; Color; CreateFcn; DeleteFcn; EraseMode; HandleVisibility; HitTest; Interruptible; LineStyle; LineWidth; Marker; MarkerEdgeColor; MarkerFaceColor; MarkerSize; Parent; Selected; SelectionHighlight; Tag; Type; UIContextMenu; UserData; Visible; XData; YData; ZData
Text
BusyAction; ButtonDownFcn; Children; Clipping; Color; CreateFcn; DeleteFcn; Editing; EraseMode; Extent; FontAngle; FontName; FontSize; FontUnits; FontWeight; HandleVisibility; HitTest; HorizontalAlignment; Interpreter; Interruptible; Parent; Position; Rotation; Selected; SelectionHighlight; String; Tag; Type; UIContextMenu; Units; UserData; VerticalAlignment; Visible
Uicontrol