KB01: Useful MATLAB Commands
A few Important Commands
Command | Description | Example |
---|---|---|
demo | Run MATLAB's built-in demonstrations | |
clc | Clear the Command Window | |
clf | Clear the contents of the current figure window | |
clear | Clear the variables in the workspace | |
CTRL + C | Abort the running program, returns a command prompt | |
diary | Keep track of everything done in the MATLAB session |
General Purpose Commands
General Purpose Commands
Operators and Special Characters
Operator | Description | Example |
---|---|---|
+ | Plus; addition operator | |
- | Minus; subtraction operator | |
* | Scalar and matrix multiplication operator | |
.* | Array multiplication operator | |
^ | Scalar and matrix exponentiation operator | |
.^ | Array exponentiation operator | |
\ | Left-division operator | |
/ | Right-division operator | |
.\ | Array left-division operator | |
./ | Array right-division operator | |
: | Colon; generates regularly spaced elements and represents an entire row or column | |
( ) | Parentheses; encloses function arguments and array indices; overrides precedence | |
[ ] | Brackets; enclosures array elements | |
. | Decimal point | |
... | Ellipsis; line-continuation operator | |
, | Comma; separates statements and elements in a row | |
; | Semicolon; separates columns and suppresses display | |
% | Percent sign; designates a comment and specifies formatting | |
_ | Quote sign and transpose operator | |
._ | Nonconjugated transpose operator | |
= | Assignment (replacement) operator |
Commands for Managing a Session
Command | Description | Example |
---|---|---|
clc | Clears Command window |
|
clear | Removes variables from memory | |
exist | Checks for the existence of file or variable | |
global | Declares variables to be globa | |
help | Searches for a help topic | |
lookfor | Searches help entries for a keyword | |
quit | Stops MATLAB | |
who | Lists current variables | |
whos | Lists current variables (long display) | |
Special Variables and Constants
Command | Description | Example |
---|---|---|
ans | Most recent answer |
|
eps | Accuracy of floating-point precision | |
i, j | The imaginary unit \(\sqrt { - 1} \) | |
Inf | Infinity | |
NaN | Undefined numerical result (not a number) | |
pi | The number π |
System and File Command
Command | Description | Example |
---|---|---|
cd | Changes current directory |
|
date | Displays current date | |
delete | Deletes a file | |
diary | Switches on/off diary file recording | |
dir | Lists all files in the current directory | |
load | Loads workspace variables from a file | |
path | Displays search path | |
pwd | Displays current directory | |
save | Saves workspace variables in a file | |
type | Displays contents of a file | |
what | Lists all MATLAB files in the current directory | |
wklread | Read .wkl spreadsheet file |
Input/Output and Formatting Commands
Input/Output and Formatting Commands
Input/Output Commands
Command | Description | Example |
---|---|---|
disp | Displays contents of an array or string |
|
fscanf | Read formatted data from a file | |
format | Controls screen-display format | |
fprintf | Performs formatted writes to screen or file | |
input | Displays prompt and waits for input | |
; | Suppresses screen printing |
Format Codes for fprintf and fscanf
Format | Description | Example |
---|---|---|
%s | Format as a string |
|
%d | Format as an integer | |
%f | Format as a floating-point value | |
%e | Format as a floating-point value in scientific notation | |
%g | Format in the most compact form: %f or %e | |
\n | Insert a new line in the output string | |
\r | Insert a tab in the output string |
Numeric Display Formats
Command | Description | Example |
---|---|---|
format short | Four decimal digits (default) |
|
format long | 16 decimal digits | |
format short e | Five digits plus exponents | |
format long e | 16 digits plus exponents | |
format bank | Two decimal digits | |
format + | Positive, negative, or zero | |
format rat | Rational approximation | |
format compact | Suppresses some line feeds | |
format loose | Reset to less compact display mode |
Vector, Matrix, and Array Commands
Vector, Matrix, and Array Commands
Array Commands
Command | Description | Example |
---|---|---|
cat | Concatenates arrays | |
find | Finds indices of nonzero elements | |
length | Computes the number of elements | |
linspace | Creates a regularly spaced vector | |
logspace | Creates a logarithmically spaced vector | |
max | Returns largest element | |
min | Returns smallest element | |
prod | Product of each column | |
reshape | Change size | |
size | Computes array size | |
sort | Sorts each column | |
sum | Sums each column |
Special Matrices
Command | Description | Example |
---|---|---|
eye | Creates an identity matrix |
|
ones | Creates an array of ones | |
zeros | Creates an array of zeros |
Matrix Arithmetic
Command | Description | Example |
---|---|---|
cross | Computes cross products |
|
dot | Computes dot products |
Matrix Commands for Solving Linear Equations
Command | Description | Example |
---|---|---|
det | Computes determinant of an array | |
inv | Computes the inverse of a matrix | |
pinv | Computes pseudoinverse of a matrix | |
rank | Computes rank of matrix | |
rref | Computes reduced row echelon form |
Cell Array Functions
Command | Description | Example |
---|---|---|
cell | Creates cell array |
|
celldisp | Displays cell array | |
cellplot | Displays graphical representation of cell array | |
num2cell | Converts numeric array to cell array | |
deal | Matches input and output lists | |
iscell | Identifies cell array |
Structure Functions
Command | Description | Example |
---|---|---|
fieldnames | Returns field names in a structure array | |
getfield | Returns field contents of a structure array | |
isfield | Identifies a structure array field | |
isstruct | Identifies a field from a structure array | |
setfield | Sets contents of the field | |
struct | Creates structure array |
Plotting Commands
Plotting Commands
Basic xy Plotting Commands
Command | Description | Example |
---|---|---|
axis | Sets axis limits |
|
fplot | Intelligent plotting of functions | |
grid | Displays gridlines | |
plot | Generates xy plot | |
Prints plot or saves plot to a file | ||
title | Puts text at top of plot | |
xlabel | Adds text label to x-axis | |
ylabel | Adds text label to y-axis |
Plot Enhancement Commands
Command | Description | Example |
---|---|---|
axes | Creates axes objects |
|
close | Closes the current objects | |
close all | Closes all plots | |
figure | Opens a new figure window | |
gtext | Enables label placement by mouse | |
hold | Freezes current plot | |
legend | Legend placement by mouse | |
refresh | Redraws current figure window | |
set | Specifies properties of objects such as axes | |
subplot | Creates plots in subwindows | |
text | Places string in figure |
Specialized Plot Commands
Command | Description | Example |
---|---|---|
bar | Creates bar chart | |
loglog | Creates log-log plot | |
polar | Creates polar plot | |
semilogx | Creates semilog plot (logarithmic abscissa) | |
semilogy | Creates semilog plot (logarithmic ordinate) | |
stairs | Creates stairs pot | |
stem | Creates stem plot |
Colors, Symbols, and Line Types
Color | Symbol | Line | ||||
---|---|---|---|---|---|---|
y | yellow | . | point | - | solid | |
m | magenta | o | circle | : | dotted | |
c | cyan | x | x-mark | -. | dash-dotted | |
r | red | + | plus | -- | dashed | |
g | green | * | star | |||
b | blue | d | diamond | |||
w | white | v | triangle (down) | |||
k | black | ^ | triangle (up) | |||
< | triangle (left) | |||||
> | triangle (right) | |||||
p | pentagram | |||||
h | hexagram |
Three-Dimensional Plotting Commands
Command | Description | Example |
---|---|---|
contour | Creates contour plot | |
mesh | Creates three-dimensional mesh surface plot | |
meshc | Same as mesh with contour plot underneath | |
meshz | Same as mesh with vertical lines underneath | |
plot3 | Creates three-dimensional plots from lines and points | |
surf | Creates shaded three-dimensional mesh surface plot | |
surfc | Same as surf with contour plot underneath | |
meshgrid | Creates rectangular grid | |
waterfall | Same as mesh with mesh lines in one direction | |
zlabel | Adds text label to z-axis |
Histogram Functions
Command | Description | Example |
---|---|---|
bar | Creates a bar chart | |
hist | Aggregates the data into equally spaced bins | |
histc | Aggregates the data into unequally spaced bins |
Programming
Programming
Logical and Relational Operators
Command | Description | Example |
---|---|---|
== | Relational operator: equal to | |
~= | Relational operator: not equal to | |
< | Relational operator: less than | |
<= | Relational operator: less than or equal to | |
> | Relational operator: greater than | |
>= | Relational operator: greater than or equal to | |
& | Logical operator: AND | |
| | Logical operator: OR | |
~ | Logical operator: NOT | |
xor | Logical operator: EXCLUSIVE OR |
Program Flow Control
Command | Description | Example |
---|---|---|
break | Terminates execution of a loop | |
case | Provides alternate execution paths within switch structure | |
else | Delineates alternate block of statements | |
elseif | Conditionally executes statements | |
end | Terminates for, while, and if statements | |
error | Display error messages | |
for | Repeats statements a specific number of times | |
if | Executes statements conditionally | |
otherwise | Default part of switch statement | |
return | Return to the invoking function | |
switch | Directs program execution by comparing point with case expressions | |
warning | Display a warning message | |
while | Repeats statements an indefinite number of times |
Logical Functions
Command | Description | Example |
---|---|---|
any | True if any elements are nonzero | |
all | True if all elements are nonzero | |
find | Finds indices of nonzero elements | |
finite | True if elements are finite | |
isnan | True if elements are undefined | |
isinf | True if elements are infinite | |
isempty | True if matrix is empty | |
isreal | True if all elements are real |
M-Files
Command | Description | Example |
---|---|---|
eval | Interpret strings containing Matlab expressions | |
feval | Function evaluation | |
function | Creates a user-defined function M-file | |
global | Define global variables | |
nargin | Number of function input arguments | |
nargout | Number of function output arguments | |
script | Script M-files |
Timing
Command | Description | Example |
---|---|---|
cputime | CPU time in seconds | |
clock | Current date and time as date vector | |
tic, toc | Start, stop a stopwatch timer |
Mathematical Functions
Mathematical Functions
Exponential and Logarithmic Functions
Command | Description | Example |
---|---|---|
exp(x) | Exponential; ex | |
log(x) | Natural logarithm; ln(x) | |
log10(x) | Common (base 10) logarithm; log(x)= log10(x) | |
sqrt(x) | Square root; |
Trigonometric Functions
Command | Description | Example |
---|---|---|
sin(x) | Sine; sin(x) | |
cos(x) | Cosine; cos(x) | |
tan(x) | Tangent; tan(x) | |
cot(x) | Cotangent; cot(x) | |
sec(x) | Secant; sec(x) | |
csc(x) | Cosecant; csc(x) | |
asin(x) | Inverse sine; arcsin x = sin–1(x) | |
acos(x) | Inverse cosine; arcos x = cos–1(x) | |
atan(x) | Inverse tangent; arctan x = tan–1(x) | |
acot(x) | Inverse cotangent; arccot x = cot–1(x) | |
asec(x) | Inverse secant; arcsec x = sec–1(x) | |
acsc(x) | Inverse cosecant; arcs x = csc–1(x) | |
atan2(x, y) | Four-quadrant inverse tangent |
Hyperbolic Functions
Command | Description | Example |
---|---|---|
sinh(x) | Hyperbolic sine; sinh(x) | |
cosh(x) | Hyperbolic cosine; cosh(x) | |
tanh(x) | Hyperbolic tangent; sinh(x)/cosh(x) | |
coth(x) | Hyperbolic cotangent; cosh(x)/sinh(x) | |
sech(x) | Hyperbolic secant; 1/cosh(x) | |
csch(x) | Hyperbolic cosecant; 1/sinh(x) | |
asinh(x) | Inverse hyperbolic sine; sinh-1(x) | |
acosh(x) | Inverse hyperbolic cosine; cosh-1(x) | |
atanh(x) | Inverse hyperbolic tangent; tanh-1(x) | |
acoth(x) | Inverse hyperbolic cotangent; coth-1(x) | |
asech(x) | Inverse hyperbolic secant; sech-1(x) | |
acsch(x) | Inverse hyperbolic cosecant; csch-1(x) |
Complex Functions
Command | Description | Example |
---|---|---|
abs(x) | Absolute value; |x| |
|
angle(x) | The angle of a complex number x | |
conj(x) | The complex conjugate of x | |
imag(x) | The imaginary part of a complex number x | |
real(x) | The real part of a complex number x |
Statistical Functions
Command | Description | Example |
---|---|---|
erf(x) | Computes the error function erf(x) |
|
mean | Calculates the average | |
median | Calculates the median | |
std | Calculates the standard deviation |
Random Number Functions
Command | Description | Example |
---|---|---|
rand | Generates uniformly distributed random numbers between 0 and 1 | |
randn | Generates normally distributed random numbers |
Numeric Functions
Command | Description | Example |
---|---|---|
ceil | Rounds to the nearest integer toward ∞ |
|
fix | Rounds to the nearest integer toward zero | |
floor | Rounds to the nearest integer toward -∞ | |
round | Rounds towards the nearest integer | |
sign | Signum function |
String Functions
Command | Description | Example |
---|---|---|
findstr | Finds occurrences of a string |
|
strcmp | Compares strings | |
char | Creates character string array |
Numerical Methods
Numerical Methods
Polynomial and Regression Functions
Command | Description | Example |
---|---|---|
conv | Computes the product of two polynomials |
|
deconv | Computes the ratio of polynomials | |
eig | Computes the eigenvalues of a matrix | |
poly | Computes polynomial from roots | |
polyfit | Fits a polynomial to data | |
polyval | Evaluates polynomial and generates error estimates | |
roots | Computes polynomial roots |
Interpolation Functions
Command | Description | Example |
---|---|---|
interp1 | Linear and cubic-spline interpolations of a function of one variable | |
interp2 | Linear interpolation of a function of two variables | |
spline | Cubic-spline interpolation | |
unmkpp | Computes the coefficients of cubic-spine polynomials |
Root Finding and Minimization
Command | Description | Example |
---|---|---|
fmin | Finds minimum of single-variable function | |
fmins | Finds minimum of multivariable function | |
fzero | Finds zero of single-variable function |
Numerical Integration Functions
Command | Description | Example |
---|---|---|
quad | Numerical integration with adaptive Simpson's rule | |
quad1 | Numerical integration with adaptive Lobatto quadrature | |
trapz | Numerical integration with the trapezoidal rule |
Numerical Differentiation Functions
Command | Description | Example |
---|---|---|
diff(x)+ | Computes the difference between adjacent elements in the vector x | |
polyder | Differentiates a polynomial, a polynomial product, or a polynomial quotient |
ODE Solvers
Command | Description | Example |
---|---|---|
ode23 | Nonstiff, low-order solver | |
ode45 | Nonstiff, medium-order solver | |
ode113 | Nonstiff, variable-order solver | |
ode23s | Stiff, low-order | |
ode23t | Moderately stiff, trapezoidal rule solver | |
ode23b | Stiff, low-order solver | |
ode15s | Stiff, variable-order solver | |
odeset | Creates integrator options structure for ODE solvers |
Predefined Input Functions
Command | Description | Example |
---|---|---|
gensig | Generates a periodic sine, square, or pulse input | |
sawtooth | Generates a periodic sawtooth input | |
square | Generates a square wave input | |
stepfun | Generates a step function input |
Symbolic Math Toolbox
Symbolic Math Toolbox
Functions for Creating and Evaluating Symbolic Expressions
Command | Description | Example |
---|---|---|
class | Returns the class of an expression | |
digits | Sets the number of decimal digits used to do variable precision arithmetic | |
double | Converts an expression to numeric form | |
ezplot | Generates a plot of a symbolic expression | |
findsym | Finds the symbolic variables in a symbolic expression | |
numden | Returns the numerator and denominator of an expression | |
sym | Creates a symbolic variable | |
syms | Creates one or more symbolic variables | |
vpa | Sets the number of digits used to evaluate expressions |
Functions for Manipulating Symbolic Expressions
Command | Description | Example |
---|---|---|
collect | Collects coefficients of like powers in an expression | |
expand | Expands an expression by carrying out powers | |
factor | Factors an expression | |
poly2sym | Converts a polynomial coefficient vector to a symbolic polynomial | |
pretty | Displays an expression in a form that resembles typeset mathematics | |
simple | Searches for the shortest form of an expression | |
simplify | Simplifies an expression using Maple's simplification rules | |
subs | Substitutes variables or expressions | |
sym2poly | Converts an expression to a polynomial coefficient vector |
Symbolic Calculus Functions
Command | Description | Example |
---|---|---|
diff | Returns the derivative of an expression | |
Dirac | Dirac delta function (unit impulse) | |
Heaviside | Heaviside function (unit step) | |
int | Returns the integral of an expression | |
limit | Returns the limit of an expression | |
symsum | Returns the symbolic summation of an expression | |
taylor | Returns the Taylor series of a function |
Symbolic Solution of Algebraic and Transcendental Equations
Command | Description | Example |
---|---|---|
solve | Solves symbolic equations |
Symbolic Solution of Differential Equations
Command | Description | Example |
---|---|---|
dsolve | Returns a symbolic solution of a differential equation or set of equations |
Laplace Transform Functions
Command | Description | Example |
---|---|---|
laplace | Returns the Laplace transform | |
ilaplace | Returns the inverse Laplace transform |
Symbolic Linear Algebra Functions
Command | Description | Example |
---|---|---|
det | Returns the determinant of a matrix | |
eig | Returns the eigenvalues (characteristic roots) of a matrix | |
inv | Returns the inverse of a matrix | |
poly | Returns the characteristic polynomial of a matrix |
Inverse Commands
Inverse Commands
Using lookfor inverse command to list the functions that take the inverse of the matrix.
Functions for Creating and Evaluating Symbolic Expressions
Command | Description | Example |
---|---|---|
ifft | Inverse discrete Fourier transform | |
ifft2 | Two-dimensional inverse discrete Fourier transform | |
ifftn | N-dimensional inverse discrete Fourier transform | |
ifftshift | Inverse FFT shift | |
asin | Inverse sine, result in radians | |
asind | Inverse sine, result in degrees | |
asinh | Inverse hyperbolic sine | |
acos | Inverse cosine, result in radians | |
acosd | Inverse cosine, result in degrees | |
acosh | Inverse hyperbolic cosine | |
atan | Inverse tangent, result in radians | |
atan2 | Four quadrant inverse tangent | |
atan2d | Four quadrant inverse tangent, result in degrees | |
atand | Inverse tangent, result in degrees | |
atanh | Inverse hyperbolic tangent | |
acot | Inverse cotangent, result in radian | |
acotd | Inverse cotangent, result in degrees | |
acoth | Inverse hyperbolic cotangent | |
asec | Inverse secant, result in radians | |
asecd | Inverse secant, result in degrees | |
asech | Inverse hyperbolic secant | |
acsc | Inverse cosecant, result in radian | |
acscd | Inverse cosecant, result in degrees | |
acsch | Inverse hyperbolic cosecant | |
invhilb | Inverse Hilbert matrix | |
ipermute | Inverse permute array dimensions | |
inv | Matrix inverse | |
pinv | Pseudoinverse | |
betaincinv | Inverse incomplete beta function | |
erfcinv | Inverse complementary error function | |
erfinv | Inverse error function | |
gammaincinv | Inverse incomplete gamma function | |
acde | Inverse of cd elliptic function | |
asne | Inverse of sn elliptic function | |
icceps | Inverse complex cepstrum | |
idct | Inverse discrete cosine transform | |
ifwht | Fast Inverse Discrete Walsh-Hadamard Transform | |
unshiftdata | The inverse of SHIFTDATA |