title: MATLAB
date: 2023-01-03 09:51:44
background: bg-[#692316]
tags:
categories:
- Programming
intro: |
This quick reference cheat sheet provides an example introduction to using the MATLAB scientific computing language to get started quickly
Getting Started
Introduction
MATLAB is short for matrix laboratory
MATLAB allows you to use a single arithmetic operator or function to manipulate all values in a matrix
a + 10
MATLAB will execute the above statement and return the following results:
ans = 3×3
11 13 15
12 14 16
17 18 20
sin(a)
MATLAB will execute the above statement and return the following results:
ans = 3×3
0.8415 0.1411 -0.9589
0.9093 -0.7568 -0.2794
0.6570 0.9894 -0.5440
To transpose a matrix, use single quotes ('
)
a'
ans = 3×3
1 2 7
3 4 8
5 6 10
Perform standard matrix multiplication using the *
operator, which computes the inner product between rows and columns
p = a*inv(a)
p = 3×3
1.0000 0 0
0 1.0000 0
0 0 1.0000
concatenation {.row-span-2}
Concatenation is the process of joining arrays to form larger arrays. In fact, the first array is formed by concatenating its elements. Pairs of square brackets []
are concatenation operators.
A = [a,a]
A = 3×6
1 3 5 1 3 5
2 4 6 2 4 6
7 8 10 7 8 10
Concatenating arrays next to each other using commas is called horizontal concatenation. Each array must have the same number of rows. Likewise, semicolons can be used for vertical concatenation if the arrays have the same number of columns.
A = [a; a]
A = 6×3
1 3 5
2 4 6
7 8 10
1 3 5
2 4 6
7 8 10
Matrices and arrays{.row-span-3}
To create an array with four elements per row, separate elements with commas (,
) or spaces
a = [1 2 3 4]
MATLAB will execute the above statement and return the following results:
a = 1×4
1 2 3 4
Create a matrix with multiple rows
a = [1 3 5; 2 4 6; 7 8 10]
a = 3×3
1 3 5
2 4 6
7 8 10
5×1 column vector of zeros
z = zeros(5,1)
z = 5×1
0
0
0
0
0
Complex number
A complex number has a real part and an imaginary part, and the imaginary unit is the square root of -1.
sqrt(-1)
ans = 0.0000 + 1.0000i
To represent the imaginary part of a complex number, use i or j.
c = [3+4i, 4+3j; -i, 10j]
c = 2×2 complex
3.0000 + 4.0000i 4.0000 + 3.0000i
0.0000 - 1.0000i 0.0000 +10.0000i
Basic knowledge
Input the command
- |
- |
- |
ans |
Most recently calculated answer |
|
clc |
Clear the command line window |
|
diary |
Record the text of the command line window into the log file |
|
format |
Set the output display format |
|
home |
Send cursor reset |
|
iskeyword |
Determine if the input is a MATLAB keyword |
|
more |
Control paging output in the command line window |
|
commandwindow |
Select command window |
|
commandhistory |
Open command history window |
|
Objects
Matrices and Arrays {.row-span-5}
Create and combine arrays
- |
- |
- |
zeros |
Create an array of all zeros |
|
ones |
Create an array of all 1s |
|
rand |
Uniformly distributed random numbers |
|
true |
Logical value 1 (true) |
|
false |
logical 0 (false) |
|
eye |
identity matrix |
|
diag |
Create a diagonal matrix or get the diagonal elements of a matrix |
|
blkdiag |
block diagonal matrix |
|
cat |
Concatenate arrays. |
|
horzcat |
Concatenate arrays horizontally |
|
vertcat |
Concatenate arrays vertically |
|
repelem |
Repeat array element copy |
|
repmat |
Repeat array copy |
|
create grid
- |
- |
- |
linspace |
Generate linearly spaced vectors |
|
logspace |
Generate logarithmic spaced vectors |
|
freqspace |
frequency spacing of frequency response |
|
meshgrid |
2D and 3D grids |
|
ndgrid |
Rectangular grid in N-dimensional space |
|
Determine size, shape and order
- |
- |
- |
length |
The length of the largest array dimension |
|
size |
array size |
|
ndims |
Number of dimensions of the array |
|
numel |
the number of array elements |
|
isscalar |
Determine whether the input is a scalar |
|
issorted |
Determine if the array is sorted |
|
issortedrows |
Determine whether the rows of a matrix or table are sorted |
|
isvector |
Determine whether the input is a vector |
|
ismatrix |
Determine whether the input is a matrix |
|
isrow |
Determine whether the input is a row vector |
|
iscolumn |
Determine whether the input is a column vector |
|
isempty |
Determine whether the array is empty |
|
Refactor and rearrange
- |
- |
- |
sort |
Sort array elements |
|
sortrows |
Sort matrix rows or table rows |
|
flip |
Flip the order of elements |
|
fliplr |
Flip the array from left to right |
|
flipud |
Flip the array from top to bottom |
|
rot90 |
Rotate an array by 90 degrees |
|
transpose |
Transpose a vector or matrix |
|
ctranspose |
complex conjugate transpose |
|
permute |
permute array dimension |
|
ipermute |
Inverse permutation of array dimensions. |
|
circshift |
Circular shift array |
|
shiftdim |
shift array dimension |
|
reshape |
Reshape array |
|
squeeze |
Remove dimensions of length 1 |
|
index
- |
- |
- |
colon |
vector creation, array subscript and for loop iteration |
|
end |
Terminate a code block or indicate the maximum array index |
|
ind2sub |
Convert linear index to subscript |
|
sub2ind |
Convert subscript to linear index |
|
Value type {.row-span-2}
Create numeric variables
- |
- |
- |
double |
double precision array |
|
single |
single precision array |
|
int8 |
8-bit signed integer array |
|
int16 |
16-bit signed integer array |
|
int32 |
32-bit signed integer array |
|
int64 |
64-bit signed integer array |
|
uint8 |
Array of 8-bit unsigned integers |
|
uint16 |
16-bit unsigned integer array |
|
uint32 |
32-bit unsigned integer array |
|
uint64 |
64-bit unsigned integer array |
|
Convert between numeric types
- |
- |
- |
cast |
Convert variables to different data types |
|
typecast |
Convert data types without changing the underlying data |
|
query type and value
Value range
- |
- |
- |
eps |
Floating point relative precision |
|
flintmax |
The largest consecutive integer in floating point format |
|
Inf |
Create an array with all values Inf |
|
intmax |
The maximum value of a specific integer type |
|
intmin |
The minimum value of a specific integer type |
|
NaN |
Create an array where all values are NaN |
|
realmax |
The largest positive floating point number |
|
realmin |
Minimum standard floating point number |
|
Loops and conditional statements
- |
- |
if, elseif, else |
Execute statement when condition is true |
switch, case, otherwise |
Execute one of multiple sets of statements |
for |
A for loop used to repeat a specified number of times |
while |
A while loop that executes repeatedly while a condition is true |
try, catch |
Execute the statement and catch the resulting error |
break |
Terminate execution of a for or while loop |
return |
Return control to the calling script or function |
continue |
Passes control to the next iteration of a for or while loop |
pause |
Temporarily suspend the execution of MATLAB |
parfor |
Parallel for loop |
end |
Terminate a code block or indicate the maximum array index {.style-list} |
Array of strings
- |
- |
- |
string |
string array |
|
strings |
Create a string array that does not contain characters |
|
join |
Merge strings |
|
plus |
Add numbers, append strings |
|
Character array
- |
- |
- |
char |
character array |
|
cellstr |
Convert to a cell array of character vectors |
|
blanks |
Create a blank character array |
|
newline |
Create newline |
|
Character or string array
- |
- |
- |
compose |
Format data into multiple strings |
|
sprintf |
Format data as string or character vector |
|
strcat |
Concatenate strings horizontally |
|
append |
Merge strings |
|
Char or string -convert input arguments
CHAR or STRING -convert between numeric and string
- |
- |
- |
double |
double precision array |
|
string |
string array |
|
str2double |
Convert a string to a double value |
|
num2str |
Convert numbers to character arrays |
|
Character or string -determine type and attributes {.row-span-2}
type of data
- |
- |
- |
ischar |
Determine whether the input is a character array |
|
iscellstr |
Determines if input is a cell array of character vectors |
|
isstring |
Determine whether the input is an array of strings |
|
isStringScalar |
Determine whether the input is a string array containing one element |
|
text attribute
- |
- |
- |
strlength |
string length |
|
isstrprop |
Determine which characters in the input string belong to the specified category |
|
isletter |
Determine which characters are letters |
|
isspace |
Determine which characters are whitespace characters |
|
character or string -find and replace {.row-span-2}
look up
- |
- |
- |
contains |
Determine if there is a pattern in the string |
|
matches |
Determine if a pattern matches a string |
|
count |
Count the number of occurrences of a pattern in a string |
|
endsWith |
Determine if a string ends with a pattern |
|
startsWith |
Determine whether a string starts with a pattern |
|
strfind |
Find a string in other strings |
|
sscanf |
Read formatted data from a string |
|
replace
- |
- |
- |
replace |
Find and replace one or more substrings |
|
replaceBetween |
Replace the substring between the start and end |
|
strrep |
Find and replace substring |
|
String matching pattern -build pattern
- |
- |
- |
pattern |
pattern for searching and matching text |
|
String match pattern -character match pattern
String matching pattern -pattern search rules
String matching pattern -Boundary pattern {.row-span-2}
String matching pattern -custom pattern display
String matching pattern -regular expression
- |
- |
- |
regexp |
match regular expression (case sensitive) |
|
regexpi |
Match regular expressions (case insensitive) |
|
regexprep |
Replace text using regular expressions |
|
regexptranslate |
Convert text to regular expressions |
|
regexpPattern |
Match the pattern of the specified regular expression |
|
String matching pattern -join and split
- |
- |
- |
join |
Merge strings |
|
plus |
Add numbers, append strings |
|
split |
Split string at delimiter |
|
splitlines |
Split a string at newlines |
|
strjoin |
join the strings in the array |
|
strsplit |
Splits a string or character vector at the specified delimiter |
|
strtok |
Selected string part |
|
extract |
Extract a substring from a string |
|
extractAfter |
Extract the substring after the specified position |
|
extractBefore |
Extract the substring before the specified position |
|
extractBetween |
Extract the substring between the starting point and the ending point |
|
String editing {.row-span-2}
- |
- |
- |
erase |
Delete a substring in a string |
|
eraseBetween |
Delete the substring between the start and end |
|
extract |
Extract a substring from a string |
|
extractAfter |
Extract the substring after the specified position |
|
extractBefore |
Extract the substring before the specified position |
|
extractBetween |
Extract the substring between the starting point and the ending point |
|
insertAfter |
Insert a string after the specified substring |
|
insertBefore |
Insert a string before the specified substring |
|
pad |
Add leading or trailing characters to a string |
|
strip |
Remove leading and trailing characters in a string |
|
lower |
convert string to lowercase |
|
upper |
convert string to uppercase |
|
reverse |
Reverse the order of characters in a string |
|
deblank |
Remove trailing blanks at the end of a string |
|
strtrim |
Remove leading and trailing blanks from a string |
|
strjust |
align string |
|
String comparison
- |
- |
- |
matches |
Determine if a pattern matches a string |
|
strcmp |
Compare strings |
|
strcmpi |
Compare strings (case insensitive) |
|
strncmp |
compares the first n characters of a string (case sensitive) |
|
strncmpi |
Compare the first n characters of a string (case insensitive ) |
|
Basic Arithmetic {.row-span-3}
Addition
- + Add numbers, append strings
- sum sum of array elements
- cumsum cumulative sum
- movsum moving sum {.cols-2 style-none}
Subtraction
- - subtraction
- diff difference and approximate derivative {.cols-2 style-none}
Multiplication
- |
- |
- |
.* |
Multiplication |
|
* |
Matrix multiplication |
|
prod |
product of array elements |
|
cumprod |
cumulative product |
|
pagemtimes |
Matrix multiplication by page |
|
tensorprod |
Tensor products between two tensors |
|
Division
Power
- .^ Element-wise exponentiation
- ^ matrix power {.cols-2}
Transpose
- |
- |
- |
.' |
Transpose a vector or matrix |
|
' |
complex conjugate transpose |
|
pagetranspose |
Transpose by page |
|
pagectranspose |
Complex conjugate transpose by page |
|
Array notation
- uminus unary subtraction
- uplus unary addition {.cols-2}
Modular division and rounding
- |
- |
- |
mod |
Remainder after division (modulo operation) |
|
rem |
Remainder after division |
|
idivide |
Divisibility with rounding options |
|
ceil |
round towards positive infinity |
|
fix |
round towards zero |
|
floor |
round towards negative infinity |
|
round |
round to the nearest decimal or integer |
|
Custom Binary Functions
- |
- |
- |
bsxfun |
Apply element-wise operations on two arrays (with implicit expansion enabled) |
|
Relational operations
value comparison
- |
- |
- |
== |
Determine equality |
|
>= |
Determine greater than or equal to |
|
> |
Determine greater than |
|
<= |
Determine less than or equal to |
|
< |
Determine less than |
|
~= |
Determine Inequality |
|
isequal |
Determine array equality |
|
isequaln |
Test array equality, treat NaN values as equal |
|
Logical (Boolean) operations
true or false condition
- |
- |
- |
Short-circuit &&, || |
Logical operators with short-circuit function |
|
& |
Computational logic AND |
|
~ |
Computational logic NOT |
|
| |
Calculation logic OR |
|
xor |
Compute logical exclusive OR |
|
all |
Determine whether all array elements are non-zero or true |
|
any |
Determine if any array elements are non-zero |
|
false |
logical 0 (false) |
|
find |
Find the index and value of non-zero elements |
|
islogical |
Determine whether the input is a logical array |
|
logical |
Convert numeric values to logical values |
|
true |
Logical value 1 (true) |
|
Set operation
union, intersection, set relationship
- |
- |
- |
intersect |
Set the intersection of two arrays |
|
ismember |
Determine whether an array element is a set array member |
|
setdiff |
Set the difference between two arrays |
|
setxor |
Set XOR of two arrays |
|
union |
Set the union of two arrays |
|
unique |
Unique value in an array |
|
ismembertol |
set membership within tolerance |
|
uniquetol |
unique values within tolerance |
|
join |
Merge two tables or timetables row by row using a key variable |
|
innerjoin |
Inner join between two tables or timetables |
|
outerjoin |
Outer join between two tables or timetables |
|
Bitwise operations
set, offset, or compare specific bitfields
Data import and export
text file -read and write table or timetable {.row-span-2}
Basic import and export
Define import rules
{.style-list}
Text files -read and write matrices and arrays
Spreadsheet -Read and Write Table or Timetable {.row-span-2}
Basic import and export
{.style-list}
Define import rules
Spreadsheet -Reading and writing matrices and arrays
images
- |
- |
- |
imfinfo |
Information about graphics files |
|
imread |
Reads an image from a graphics file |
|
imwrite |
Writes an image to a graphics file |
|
Tiff |
MATLAB entry for LibTIFF library routines |
|
Read or write a NetCDF file {.row-span-2}
- |
- |
- |
nccreate |
Create variables in a NetCDF file |
|
ncdisp |
Displays NetCDF data source content in the command line window |
|
ncinfo |
Returns information about a NetCDF data source |
|
ncread |
Read variable data from a NetCDF data source |
|
ncreadatt |
Read attribute values in a NetCDF data source |
|
ncwrite |
Write data to a NetCDF file |
|
ncwriteatt |
Write attributes to a NetCDF file |
|
ncwriteschema |
Adds a NetCDF schema definition to a NetCDF file |
|
NetCDF library package -library functions
NetCDF library package -file operations {.row-span-2}
NetCDF Library Package -Dimensions
NetCDF library package -group
NetCDF library package -variable {.row-span-3}
NetCDF library package -properties
NetCDF library package -user-defined types
NetCDF library package -Utilities
Read or write HDF5 files
HDF5 library package {.row-span-4}
HDF4 Files -Advanced Functions
- |
- |
hdfinfo |
Information about HDF4 or HDF-EOS files |
hdfread |
Read data from HDF4 or HDF-EOS files |
imread |
Read an image from a graphics file |
imwrite |
Write image to graphics file |
Low-level functions -package {.row-span-3}
Low Level Functions -Functions
- |
- |
hdfan |
The entry of HDF multi-file annotation (AN) interface |
hdfhx |
The entry of HDF external data (HX) interface |
hdfh |
The entry of HDF H interface |
hdfhd |
The entry of HDF HD interface |
hdfhe |
The entry of HDF HE interface |
hdfml |
Utilities for use with MATLAB HDF entry functions |
hdfpt |
Interface of HDF-EOS point object |
hdfv |
The entry of HDF Vgroup (V) interface |
hdfvf |
The entry of VF function in HDF Vdata interface |
hdfvh |
The entry of VH function in HDF Vdata interface |
hdfvs |
The entry of VS function in HDF Vdata interface |
hdfdf24 |
HDF 24-bit raster image (DF24) interface entry |
hdfdfr8 |
HDF 8-bit raster image (DFR8) interface entry |
FITS file -function
FITS files -file access
FITS files -image processing
FITS file -keyword {.row-span-2}
FITS files -Header Data Unit (HDU) access
- |
- |
copyHDU |
Copy current HDU from one file to another |
getHDUnum |
The number of the current HDU in the FITS file |
getHDUtype |
current HDU type |
getNumHDUs |
Total number of HDUs in FITS file |
movAbsHDU |
Move to Absolute HDU Numbering |
movNamHDU |
Move to the first HDU containing a specific type and keyword value |
movRelHDU |
Move relative amount of HDU from current HDU |
writeChecksum |
Calculate and write the checksum of the current HDU |
deleteHDU |
Delete the current HDU in the FITS file |
FITS files -image compression
FITS file -ASCII table and binary table {.row-span-3}
FITS files -Utilities
Stripe interleaved file
Common Data Format (CDF)
- |
- |
cdfinfo |
Information on Common Data Format (CDF) files |
cdfread |
Read data in Common Data Format (CDF) files |
cdfepoch |
Converts a date literal or date sequence value to a date in CDF format |
todatenum |
Convert CDF epoch objects to MATLAB date serial values |
Bag
- |
- |
cdflib |
Direct interaction with CDF library |
Read video data
- |
- |
VideoReader |
Create an object to read a video file |
read |
Read one or more video frames |
readFrame |
Read the next video frame |
hasFrame |
Determine whether there are video frames available for reading |
getFileFormats |
File formats supported by VideoReader |
mmfileinfo |
Information about multimedia files |
Write video data
- |
- |
VideoWriter |
Create an object to write a video file |
open |
Open a file to write video data |
writeVideo |
Write video data to a file |
close |
close the file after writing video data |
getProfiles |
Description files and file formats supported by VideoWriter |
Read or write audio
Play audio
- |
- |
audioplayer |
Object for playing audio |
isplaying |
Determine whether playback is in progress |
pause |
Pause playback or recording |
play |
Play audio from audioplayer object |
playblocking |
Play audio in audioplayer object, keep control until playback is complete |
resume |
Resume playback or recording from the paused state |
stop |
Stop playing or recording |
Record audio
- |
- |
audiorecorder |
object for recording audio |
getaudiodata |
Store the recorded audio signal in a numeric array |
getplayer |
Create an associated audioplayer object |
isrecording |
Determine if recording is in progress |
record |
Record audio into audiorecorder object |
recordblocking |
Record audio into an audiorecorder object, keep control until recording is complete |
Play sound
- |
- |
audiodevinfo |
Information about audio devices |
audiodevreset |
Refresh the list of available audio devices |
sound |
Convert signal data matrix to sound |
soundsc |
Scale data and play it as sound |
beep |
generate operating system beep |
Reading and writing XML documents
{.style-list-arrow}
W3C DOM
{.style-list-arrow}
XML Transformation
{.style-list-arrow}
XPath query
{.style-list-arrow}
JSON format
- |
- |
jsondecode |
Decode text in JSON format |
jsonencode |
Create JSON-formatted text {.style-list} from structured MATLAB data |
Workspace variables and MAT-file {.row-span-2}
- |
- |
load |
Load file variables into the workspace |
save |
Save workspace variables to a file |
matfile |
Access and change variables in a MAT-file without loading the file into memory |
disp |
Display the value of the variable |
formattedDisplayText |
Capture display output as a string |
who |
List variables in the workspace |
whos |
List variables in the workspace with their size and type |
clear |
Delete items from the workspace and release system memory |
clearvars |
Clear variables in memory |
openvar |
Open a workspace variable in the variable editor or other graphical editing tools |
Workspace Browser |
Open the Workspace Browser to manage the workspace |
Low-level file I/O {.row-span-2}
- |
- |
fclose |
close one or all open files |
feof |
Detect the end of the file |
ferror |
File I/O error message |
fgetl |
Read lines in a file and remove line breaks |
fgets |
Read lines in a file and keep newlines |
fileread |
Read file content in text format |
fopen |
Open a file or get information about opening a file |
fprintf |
Write data to a text file |
fread |
Read data in binary files |
frewind |
Move the file position indicator to the beginning of the opened file |
fscanf |
Read the data in the text file |
fseek |
Move to the specified position in the file |
ftell |
current location |
fwrite |
Write data to a binary file |
Serial and USB Communication -Connection and Configuration
Serial and USB communication -read and write
- |
- |
read |
Read data from the serial port |
readline |
Read ASCII string data line from serial port |
write |
write data to serial port |
writeline |
Write ASCII data line to serial port |
Serial and USB communication -control pins and memory
- |
- |
flush |
Clear the serial port device buffer |
getpinstatus |
Get the serial port status |
setRTS |
Set the serial port RTS pin |
setDTR |
Set the serial DTR pin |
TCP/IP communication -connection and configuration
- |
- |
tcpclient |
Create a TCP/IP client connection to a TCP/IP server |
echotcpip |
Start or stop the TCP/IP echo server |
configureTerminator |
Set terminator for ASCII string communication with remote host via TCP/IP |
configureCallback |
Set callback function and trigger condition for communication with remote host via TCP/IP {.style-list} |
TCP/IP communication -read and write
- |
- |
read |
Read data on a remote host via TCP/IP |
readline |
Read ASCII string data line from remote host via TCP/IP |
write |
Write data to a remote host via TCP/IP |
writeline |
Write ASCII data line to remote host via TCP/IP |
flush |
Flush buffers for communication with remote hosts via TCP/IP {.style-list} |
Bluetooth communication -connection and configuration
- |
- |
bluetoothlist |
Scan for nearby Bluetooth classic devices |
bluetooth |
Connect to Bluetooth classic device |
configureTerminator |
Set terminator for ASCII string communication with Bluetooth device |
configureCallback |
Set callback function and trigger condition for communication with Bluetooth device {.style-list} |
Bluetooth communication -read and write {.row-span-2}
- |
- |
read |
Read data from a Bluetooth device |
readline |
Read ASCII string data line from Bluetooth device |
write |
write data to Bluetooth device |
writeline |
Write ASCII data line to Bluetooth device |
flush |
Clear Bluetooth device buffer {.style-list} |
Bluetooth Low Energy Communication {.row-span-2}
- |
- |
blelist |
Scan for nearby low energy Bluetooth peripherals |
ble |
Connect to low energy Bluetooth peripherals |
characteristic |
Access to characteristics of Bluetooth low energy peripherals |
descriptor |
Access descriptors on Bluetooth low energy peripherals |
read |
Read characteristic or descriptor data on a Bluetooth low energy peripheral device |
write |
Write data to a characteristic or descriptor of a Bluetooth low energy peripheral device |
subscribe |
Subscribe to characteristic notifications or instructions |
unsubscribe |
Unsubscribe characteristic notifications and instructions {.style-list} |
Web Services
- |
- |
webread |
Read content from RESTful web services |
webwrite |
Write data to RESTful web service |
websave |
Save content in RESTful web service to file |
weboptions |
Specify parameters for RESTful web services |
web |
Open a webpage or file in a browser |
sendmail |
Send email to address list |
FTP file operations {.row-span-2}
- |
- |
ftp |
Connect to an FTP server to access its files |
sftp |
Connection to SFTP server to access its files |
ascii |
Set FTP transfer mode to ASCII |
binary |
Set FTP transfer mode to binary |
cd |
Change or view the current folder on an SFTP or FTP server |
close |
Close the connection to the SFTP or FTP server |
delete |
Delete files on SFTP or FTP server |
dir |
List folder contents on SFTP or FTP server |
mget |
Download files from SFTP or FTP server |
mkdir |
Create a new folder on an SFTP or FTP server |
mput |
Upload files or folders to SFTP or FTP server |
rename |
Rename a file on an SFTP or FTP server |
rmdir |
Delete a folder on an SFTP or FTP server |
Internet of Things (IoT) Data