Getting Started
Introduction
MATLAB is short for matrix laboratory
Matrix and array operations {.row-span-3}
MATLAB allows you to use a single arithmetic operator or function to manipulate all values in a matrix
MATLAB will execute the above statement and return the following results:
MATLAB will execute the above statement and return the following results:
To transpose a matrix, use single quotes ('
)
Perform standard matrix multiplication using the *
operator, which computes the inner product between rows and columns
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.
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.
Matrices and arrays {.row-span-3}
To create an array with four elements per row, separate elements with commas (,
) or spaces
MATLAB will execute the above statement and return the following results:
Create a matrix with multiple rows
a = [ 1 3 5 ; 2 4 6 ; 7 8 10 ]
5×1 column vector of zeros
Complex number
A complex number has a real part and an imaginary part, and the imaginary unit is the square root of -1.
To represent the imaginary part of a complex number, use i or j.
c = [ 3 + 4i , 4 + 3j ; -i, 10j ]
3.0000 + 4.0000i 4.0000 + 3.0000i
0.0000 - 1.0000i 0.0000 +10.0000i
Basic knowledge
- - 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
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
- - allfinite Determine if all array elements are finite anynan Determine if any array element is NaN isinteger Determine whether the input is an integer array isfloat Determine whether the input is a floating-point array isnumeric Determine whether the input is a numeric array isreal Determine whether the array uses complex storage isfinite Determine which array elements are finite isinf Determine which array elements are infinite isnan Determine which array elements are NaN
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 between numeric and string
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}
{.style-list}
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 .marker-none}
Subtraction
- subtraction
diff difference and approximate derivative
{.cols-2 .marker-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
- - ./ Array right division .\ Array left division / Solve the system of linear equations xA = B about x \ Solve the system of linear equations Ax = B with respect to x
Power
.^ Element-wise exponentiation
^ matrix power
{.cols-2 .marker-none}
Transpose
Array notation
{.cols-2 .marker-none}
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
Basic import and export
{.style-list}
Define import rules
{.style-list}
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
{.style-list}
NetCDF library package -file operations {.row-span-2}
NetCDF Library Package -Dimensions
NetCDF library package -group
NetCDF library package -variable {.row-span-3}
{.style-list}
NetCDF library package -properties
NetCDF library package -user-defined types
{.style-list}
NetCDF library package -Utilities
{.style-list}
Read or write HDF5 files
HDF5 library package {.row-span-4}
{.style-list}
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}
- - 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
- - 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}
{.style-list-arrow}
XPath query
{.style-list-arrow}
- - jsondecode Decode text in JSON format jsonencode Create JSON-formatted text 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
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
{.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