MATLAB coding cheatsheet

Useful basic commands, functions, operators and constants

Gabriele Guerini published on

Here are some useful things


Basics

CommandDescription
clcClears the command window
clearClears all variables from workspace
close allCloses all figure windows
whoLists variables in workspace
whosLists variables with details
help <function>Displays help for a function
doc <function>Opens documentation
format short/longControls display precision

Operators

Arithmetic Operators

OperatorDescriptionOperatorDescription
+Addition-Subtraction
*Multiplication^Power
.*Element-wise multiplication.^Element-wise power
/Right division\Left division
./Element-wise division

Relational Operators

OperatorDescription
==Equal
~=Not equal
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to

Logical Operators

OperatorDescription
&AND (element-wise)
&&AND (Short-circuit)
|OR (element-wise)
||OR (Short-circuit)
~NOT

Common Functions

FunctionDescription
abs(x)Absolute value
sqrt(x)Square root
exp(x)Exponential
log(x)Natural logarithm
log10(x)Base-10 logarithm
sin(x), cos(x), tan(x)Trigonometric functions
asin(x), acos(x), atan(x)Inverse trig functions
mod(a,b)Remainder after division
floor(x), ceil(x), round(x)Rounding functions

Matrix Operations

SyntaxOperation
[a b; c d]Create matrix
A'Transpose
eye(n)Identity matrix
zeros(m,n)Zeros matrix
ones(m,n)Ones matrix
rand(m,n)Random matrix
size(A)Matrix size
det(A)Matrix determinant
inv(A)Inverse matrix
eig(A)Eigenvalues
A\bSolve Ax = b

Plotting

CommandDescription
plot(x, y)2D Line plot
scatter(x, y)Scatter plot
bar(x, y)Bar chart
hist(x)Histogram
xlabel('text')X-axis label
ylabel('text')Y-axis label
title('text')Title
legend('name1', 'name2')Legend
grid on/offToggle grid

Control Flow

Conditional Statements

CommandDescription
if conditionIf statement
elseif conditionElse-if statement
elseElse statement
endEnd block

Loops

CommandDescription
for i = 1:NFor loop
while conditionWhile loop
breakBreak loop
continueSkip iteration

File I/O

CommandDescription
save filename.matSave variables to file
load filename.matLoad variables from file
csvwrite('file.csv', M)Write matrix to CSV
csvread('file.csv')Read CSV file
fopen('file.txt', 'r')Open file for reading
fclose(fid)Close file

Special Constants

ConstantValue
piπ≈3.1416
inf∞ (Infinity)
NaNNot a Number
epsMachine precision

Useful Shortcuts

ShortcutDescription
Ctrl + CStop execution
Ctrl + EnterRun current section
Ctrl + KComment selection
Ctrl + Shift + KUncomment selection
Ctrl + LClear command window