The Ultimate MATLAB Commands Cheat Sheet: A Comprehensive Reference Guide

Introduction: What is MATLAB?

MATLAB (Matrix Laboratory) is a high-performance programming language and environment for technical computing, data analysis, visualization, and algorithm development. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages.

MATLAB is widely used by engineers, scientists, mathematicians, and researchers for numerical analysis, signal processing, image processing, control systems, and more. Its integrated environment combines computation, visualization, and programming in an easy-to-use platform with powerful built-in functions.

Core Concepts and Principles

Basic Principles

  • Matrix-based computation: Everything in MATLAB is fundamentally a matrix
  • Vectorized operations: Apply operations to entire arrays without explicit loops
  • Dynamically typed: Variable types are determined at runtime
  • Interactive and scripted execution: Run commands directly or save as scripts
  • Object-oriented programming: Create and use classes and objects
  • Integrated visualization: Built-in functions for plotting and visualization

MATLAB Working Environment

ComponentDescription
Command WindowInteractive terminal to execute commands
WorkspaceArea that stores all variables
EditorInterface for writing and editing scripts
Current FolderDirectory where MATLAB looks for files by default
Command HistoryRecord of previously executed commands
Variable ExplorerTool for inspecting variables in the workspace
App GalleryCollection of interactive applications

Getting Started with MATLAB

Basic Commands and Operations

CommandDescription
help function_nameDisplay help for specified function
clcClear Command Window
clearRemove items from workspace
clear allRemove all variables from workspace
close allClose all figures
whoList variables in workspace
whosList variables with sizes and types
exit or quitExit MATLAB
ctrl+cInterrupt current operation
format short/longControl number display format
diary filenameSave Command Window text to file
pathDisplay search path
addpathAdd directories to search path

Variables and Data Types

OperationSyntaxDescription
Assignmentx = 5Assign value to variable
Multiple assignments[a,b] = deal(1,2)Assign multiple values
Arraya = [1 2 3]Create row vector
Column vectora = [1; 2; 3]Create column vector
MatrixA = [1 2; 3 4]Create 2×2 matrix
Cell arrayC = {1, 'text', [1 2]}Create heterogeneous container
StructureS.name = 'value'Create field-based structure
Stringsstr = "text"Create string object
Character arraystr = 'text'Create character array
LogicalL = trueBoolean true or false value

Operators and Special Characters

Arithmetic Operators

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Matrix multiplicationA * B
.*Element-wise multiplicationA .* B
/Right divisionA / B
./Element-wise right divisionA ./ B
\Left divisionA \ B
.\Element-wise left divisionA .\ B
^Matrix powerA ^ 2
.^Element-wise powerA .^ 2
'Complex conjugate transposeA'
.'TransposeA.'

Relational Operators

OperatorDescriptionExample
<Less thana < b
<=Less than or equala <= b
>Greater thana > b
>=Greater than or equala >= b
==Equal toa == b
~=Not equal toa ~= b

Logical Operators

OperatorDescriptionExample
&Logical ANDa & b
``Logical OR
~Logical NOT~a
&&Short-circuit ANDa && b
` `
xorExclusive ORxor(a, b)

Special Characters

CharacterDescriptionExample
[]Array constructora = [1 2 3]
()Function argument, indexingsin(x), A(1,2)
{}Cell array constructor, indexingc = {1, 'text'}, c{1}
.Structure field access, decimal points.field, 3.14
,Separator for function argumentsmax(x, y)
;Suppress output, row separatorx = 5;
%Comment% This is a comment
...Line continuationa = 1 + 2 + ...
:Range operator, all elements1:5, A(:, 1)
@Function handle@sin

Matrix Creation and Manipulation

Creating Matrices

FunctionDescriptionExample
zerosMatrix of zeroszeros(3, 4)
onesMatrix of onesones(2)
eyeIdentity matrixeye(3)
randUniform random numbersrand(3, 4)
randnNormal random numbersrandn(3, 4)
magicMagic squaremagic(3)
linspaceLinearly spaced vectorlinspace(0, 1, 5)
logspaceLogarithmically spaced vectorlogspace(0, 2, 5)
meshgrid2D and 3D grids[X, Y] = meshgrid(1:3, 1:4)
diagDiagonal matrix or diagonal of matrixdiag([1 2 3])
blkdiagBlock diagonal matrixblkdiag(A, B)
repmatReplicate and tile matrixrepmat(A, 2, 3)
catConcatenate arrayscat(dim, A, B, ...)

Matrix Manipulation

FunctionDescriptionExample
sizeArray dimensionssize(A)
lengthLength of vectorlength(x)
ndimsNumber of dimensionsndims(A)
numelNumber of elementsnumel(A)
reshapeReshape arrayreshape(A, 2, 6)
squeezeRemove singleton dimensionssqueeze(A)
permutePermute array dimensionspermute(A, [2 1 3])
ipermuteInverse permuteipermute(A, [2 1 3])
flipFlip arrayflip(A)
fliplrFlip array left to rightfliplr(A)
flipudFlip array up to downflipud(A)
rot90Rotate array 90 degreesrot90(A)
circshiftShift array circularlycircshift(A, [1 -2])
shiftdimShift dimensionsshiftdim(A, 1)
transposeNon-conjugate transposetranspose(A)
ctransposeComplex conjugate transposectranspose(A)

Matrix Indexing and Slicing

OperationDescriptionExample
Linear indexingAccess by single indexA(5)
Subscripted indexingAccess by row, columnA(2, 3)
Range indexingAccess range of elementsA(1:3, 2:4)
Logical indexingAccess by logical arrayA(A > 5)
Colon operatorAll elements in dimensionA(:, 2)
End referenceLast indexA(end, :)
Cell contentAccess cell contentsC{1}
Structure fieldAccess structure fieldS.fieldname
Dynamic field namesComputed field accessS.(variable)
Multiple outputsGet multiple elements[a, b, c] = deal(C{:})

Control Flow and Programming Constructs

Conditional Statements

% if-elseif-else statement
if condition1
    statements1
elseif condition2
    statements2
else
    statements3
end

% switch statement
switch expression
    case value1
        statements1
    case {value2, value3}
        statements2
    otherwise
        statements3
end

% try-catch statement
try
    statements
catch ME
    error_handling_statements
end

Loops

% for loop
for i = vector
    statements
end

% while loop
while condition
    statements
end

% break statement - exit loop
for i = 1:10
    if i > 5
        break
    end
end

% continue statement - skip to next iteration
for i = 1:10
    if i == 5
        continue
    end
end

Functions

% Basic function
function [output1, output2] = functionName(input1, input2)
    % function body
    output1 = input1 + input2;
    output2 = input1 * input2;
end

% Anonymous function
f = @(x) x^2 + 2*x + 1;

% Nested function
function parentFunc()
    x = 5;
    
    function nestedFunc()
        % Can access x from parent scope
        disp(x);
    end
    
    nestedFunc();
end

% Function handles
fh = @sin;
result = fh(pi/2);

Data Import/Export and File I/O

File Operations

FunctionDescriptionExample
pwdCurrent directorypwd
cdChange directorycd 'path'
dir or lsList directory contentsdir
mkdirCreate directorymkdir('newdir')
rmdirRemove directoryrmdir('dir')
deleteDelete filedelete('file.txt')
copyfileCopy filecopyfile('source', 'dest')
movefileMove filemovefile('source', 'dest')
existCheck if file or variable existsexist('file.m', 'file')
whichFull path to functionwhich('sin')
whatFunctions in directorywhat
typeDisplay contents of filetype('file.m')
filepartsParse filename parts[p, n, e] = fileparts('file.txt')
fullfileBuild full file namefullfile('dir', 'file.txt')

Data Import/Export

FunctionDescriptionExample
loadLoad variables from fileload('data.mat')
saveSave variables to filesave('data.mat', 'x', 'y')
readtableRead tabular dataT = readtable('data.csv')
writetableWrite tabular datawritetable(T, 'data.csv')
readmatrixRead matrix from fileA = readmatrix('data.txt')
writematrixWrite matrix to filewritematrix(A, 'data.txt')
readcellRead cell array from fileC = readcell('data.xlsx')
writecellWrite cell array to filewritecell(C, 'data.xlsx')
csvreadRead CSV file (legacy)csvread('data.csv')
csvwriteWrite CSV file (legacy)csvwrite('data.csv', A)
xlsreadRead Excel file (legacy)[num, txt] = xlsread('data.xlsx')
xlswriteWrite Excel file (legacy)xlswrite('data.xlsx', A)
importdataImport data from filedata = importdata('file.dat')
audioreadRead audio file[y, Fs] = audioread('audio.wav')
audiowriteWrite audio fileaudiowrite('audio.wav', y, Fs)
imreadRead imageimg = imread('image.jpg')
imwriteWrite imageimwrite(img, 'image.png')

Text File I/O

% Reading text file
fid = fopen('file.txt', 'r');
if fid ~= -1
    data = textscan(fid, '%f %s');
    fclose(fid);
end

% Writing text file
fid = fopen('file.txt', 'w');
if fid ~= -1
    fprintf(fid, 'Value: %f\n', 3.14);
    fclose(fid);
end

Data Analysis and Statistics

Basic Statistics

FunctionDescriptionExample
minMinimum valuemin(A)
maxMaximum valuemax(A)
meanAveragemean(A)
medianMedian valuemedian(A)
modeMost frequent valuemode(A)
stdStandard deviationstd(A)
varVariancevar(A)
covCovariancecov(A, B)
corrcoefCorrelation coefficientscorrcoef(A, B)
sortSort arraysort(A)
sortrowsSort rows of matrixsortrows(A, 2)
histcountsHistogram bin countshistcounts(A)
prctilePercentilesprctile(A, [25 50 75])
quantileQuantilesquantile(A, [0.25 0.5 0.75])
iqrInterquartile rangeiqr(A)
rangeRange of valuesrange(A)
cumsumCumulative sumcumsum(A)
cumprodCumulative productcumprod(A)
diffDifferencesdiff(A)
gradientNumerical gradientgradient(A)

Linear Algebra

FunctionDescriptionExample
invMatrix inverseinv(A)
pinvPseudoinversepinv(A)
detDeterminantdet(A)
traceSum of diagonal elementstrace(A)
normMatrix or vector normnorm(A)
rankRank of matrixrank(A)
nullNull spacenull(A)
orthOrthonormal basisorth(A)
eigEigenvalues and eigenvectors[V, D] = eig(A)
svdSingular value decomposition[U, S, V] = svd(A)
cholCholesky factorizationR = chol(A)
luLU factorization[L, U, P] = lu(A)
qrQR factorization[Q, R] = qr(A)
dotDot productdot(a, b)
crossCross productcross(a, b)
kronKronecker tensor productkron(A, B)
expmMatrix exponentialexpm(A)
logmMatrix logarithmlogm(A)
sqrtmMatrix square rootsqrtm(A)
rrefReduced row echelon formrref(A)
linsolveSolve linear systemlinsolve(A, b)

Curve Fitting and Interpolation

FunctionDescriptionExample
polyfitPolynomial curve fittingp = polyfit(x, y, n)
polyvalEvaluate polynomialy_fit = polyval(p, x)
interp11-D interpolationyi = interp1(x, y, xi)
interp22-D interpolationzi = interp2(x, y, z, xi, yi)
splineCubic spline interpolationyi = spline(x, y, xi)
pchipPiecewise cubic Hermite interpolationyi = pchip(x, y, xi)
fitFit curve or surface to dataf = fit(x, y, 'poly2')
lsqcurvefitSolve nonlinear curve-fittinglsqcurvefit(@func, x0, xdata, ydata)

Visualization and Plotting

2D Plotting

FunctionDescriptionExample
plot2D line plotplot(x, y)
scatterScatter plotscatter(x, y)
barBar graphbar(x, y)
barhHorizontal bar graphbarh(x, y)
histogramHistogram plothistogram(x)
stairsStairstep plotstairs(x, y)
stemStem plotstem(x, y)
areaArea plotarea(x, y)
piePie chartpie(x)
polarPolar coordinate plotpolar(theta, rho)
loglogLog-log scale plotloglog(x, y)
semilogxSemilog scale (x-axis)semilogx(x, y)
semilogySemilog scale (y-axis)semilogy(x, y)
errorbarError bar ploterrorbar(x, y, err)
boxplotBox plotboxplot(data)
plotmatrixScatter plot matrixplotmatrix(X)
contourContour plotcontour(X, Y, Z)
contourfFilled contour plotcontourf(X, Y, Z)
quiverVector plotquiver(X, Y, U, V)
compassCompass plotcompass(u, v)
featherFeather plotfeather(u, v)
fplotFunction plotfplot(@sin, [0, 2*pi])

3D Plotting

FunctionDescriptionExample
plot33D line plotplot3(x, y, z)
scatter33D scatter plotscatter3(x, y, z)
surf3D surface plotsurf(X, Y, Z)
surfcSurface with contoursurfc(X, Y, Z)
mesh3D mesh plotmesh(X, Y, Z)
meshcMesh with contourmeshc(X, Y, Z)
contour33D contour plotcontour3(X, Y, Z)
isosurfaceIsosurface from 3D dataisosurface(X, Y, Z, V)
sliceVolumetric slice plotslice(X, Y, Z, V, xi, yi, zi)
streamline3D streamlinesstreamline(X, Y, Z, U, V, W, startx, starty, startz)
coneplot3D velocity vectorsconeplot(X, Y, Z, U, V, W, cx, cy, cz)

Plot Customization

FunctionDescriptionExample
figureCreate figure windowfigure
subplotCreate subplotsubplot(2, 2, 1)
titleAdd titletitle('Plot Title')
xlabelAdd x-axis labelxlabel('X Label')
ylabelAdd y-axis labelylabel('Y Label')
zlabelAdd z-axis labelzlabel('Z Label')
legendAdd legendlegend('Data 1', 'Data 2')
gridAdd grid linesgrid on
boxToggle plot boxbox off
axisControl axis scaling and appearanceaxis equal
xlimSet x-axis limitsxlim([0, 10])
ylimSet y-axis limitsylim([-1, 1])
zlimSet z-axis limitszlim([0, 5])
colormapSet colormapcolormap(jet)
colorbarAdd color barcolorbar
caxisSet color axis limitscaxis([0, 1])
viewSet viewpointview(3)
shadingControl surface shadingshading flat
lightingControl lightinglighting gouraud
textAdd text to plottext(x, y, 'Text')
annotationAdd annotationannotation('arrow', [x1 x2], [y1 y2])
holdHold current plothold on

Common Challenges and Solutions

Memory Management

ChallengeSolution
Out of memoryUse sparse matrices for large, sparse data
 Process data in chunks
 Clear unused variables with clear
 Use single precision with single()
Large file processingUse memory-mapped files with memmapfile
 Use datastore for big data
Slow loopsVectorize operations when possible
 Preallocate arrays before loops
 Use arrayfun or cellfun for element-wise operations

Debugging

FunctionDescriptionExample
dbstopSet breakpointdbstop in file at line
dbclearClear breakpointdbclear all
dbcontContinue executiondbcont
dbstepExecute one linedbstep
dbquitQuit debug modedbquit
try/catchError handlingtry ... catch ME ... end
warningDisplay warningwarning('Warning message')
errorDisplay errorerror('Error message')
assertVerify conditionassert(condition, 'message')
profileProfile code executionprofile on/off/viewer

Common Errors and Solutions

ErrorPossible Solution
Indexing errorCheck array dimensions with size()
 Use end for last element
 Ensure indices are valid
Matrix dimensionsUse size, ndims, length to check dimensions
 Use reshape, squeeze, or permute to adjust
 Use .' for transpose (not ' for complex data)
Function not foundEnsure function is on path or in current directory
 Check spelling and case sensitivity
 Use which to locate function
Stack overflowOptimize recursion with base cases
 Consider iterative approach instead
Data type issuesCheck types with class()
 Use conversion functions like double(), int32(), etc.
 Use isa() to verify type

Best Practices and Tips

Code Optimization

  • Vectorize operations instead of using loops when possible
  • Preallocate arrays before filling them in loops
  • Use built-in functions when available (they’re typically optimized)
  • Avoid growing arrays inside loops (use preallocation)
  • Use tic/toc or timeit to profile code segments
  • Consider using the Parallel Computing Toolbox for parallel operations
  • Use sparse matrices for large, sparse data
  • Access matrices in column-major order for better performance
  • Use bsxfun for binary singleton expansion (pre-R2016b)
  • Use logical indexing instead of find when appropriate

Coding Style

  • Use meaningful variable names
  • Comment code thoroughly, especially complex sections
  • Create modular, reusable functions
  • Include error checking in functions
  • Document function inputs and outputs with help comments
  • Follow MATLAB’s naming conventions (camelCase for variables, etc.)
  • Create scripts that can run from start to finish without errors
  • Use consistent indentation and spacing
  • Avoid “magic numbers” – use named constants instead
  • Use cell mode (%%) to divide scripts into logical sections

Resources for Further Learning

Official Documentation

Books

  • “MATLAB: A Practical Introduction to Programming and Problem Solving” by Stormy Attaway
  • “MATLAB for Engineers” by Holly Moore
  • “Numerical Computing with MATLAB” by Cleve Moler

Online Resources

Scroll to Top