MATLAB Cheat Sheet For Data Science - LondonSchoolofEconomics
MATLAB Cheat Sheet For Data Science - LondonSchoolofEconomics
for i = a:s:b
Convert functions Function structure: in1 and in2 are function inputs and MATLAB Commands
out1 and out2 are function outputs. end
num2str(x) Convert numeric array (x) to char array.
num2cell(x) Convert numeric array (x) to cell array. function [out1,out2] = fun_name(in1,in2)
num2int(x) Convert numeric array (x) to signed integer. Break: break terminates the execution of for or while loop.
... Code lines after the break do not execute. In nested loops,
num2hex(x) Convert numeric array (x) to IEEE end
hexadecimal string. break exits from the loop in which it mentions.
str2num(x) Convert char array (x) to numeric array.
str2mat(x) Convert char/str array (x) to matrix. Continue: continue passes control to the next iteration of for
str2double(x) Convert char/str array (x) to double Anonymous function structure: @ operator creates a or while loop. In nested loops, continue passes the iteration in
precision. function handle. which it mentions.
str2func(x) Convert char array (x) to function handle.
cell2mat(x) Convert cell array (x) to matrix. f = @(x)(x.^2+exp(x))
cell2table(x) Convert cell array (x) to table. % i.e. f(2) returns 11.3891. Errors
cell2struct(x) Convert cell array (x) to structure array.
cellstr(x) Convert array x to cell array. Common errors
mat2str(x) Convert matrix (x) to char array. Return: return forces MATLAB to return control to the
mat2cell(x) Convert matrix (x) to cell array. invoking function before reaching to the end of that function. Error using *: inner matrix dimensions must agree.
table2cell(x) Convert table (x) to cell array. The * operator performs matrix multiplication, where an NxM
table2array(x) Convert table (x) to homogeneous array. matrix is multiplied by an MxP matrix, resulting in an NxP
table2struct(x) Convert table (x) to structure array. Flow control matrix. Use .* instead of * to perform the element-wise
struct2cell(x) Convert structure array (x) to cell array. multiplication.
struct2table(x) Convert structure array (x) to table array.
If statement: An if statement can be followed by an (or
int2str(x) Convert integer (x) to char array. Index exceeds matrix dimensions.
more) optional elseif and an else statement, which is useful
datenum(x) Convert date and time to a number. This error arises when you try to reference an element that
to test various condition.
datestr(x) Convert date and time to string. doesn’t exist. Some useful functions to check sizes and number
of elements are numel(), size(), and length().
if (Condition_1)
MATLAB Commands
Programming elseif (Condition_2)
The expression to the left of the equals sign is not a
valid target for an assignment.
MATLAB Commands This error message arises because of misuse of the = and ==
Script vs. Function vs. Live script else operators. The = operator does an assignment, and the ==
MATLAB Commands operator does a logical test for equality.
end
Script M-files: Contain a list of commands that MATLAB
simply executes in order. They are useful to batch simple Subscripted assignment dimension mismatch.
Switch statement: Evaluate a statement and selection one This error message arises because of an attempt to assign a
sequences of commonly used commands together. of the cases based on this evaluation. vector or matrix into a compartment that it does not fit in.
Function M-files: Can be executed by specifying some switch (statement) Matrix dimensions must agree.
inputs and return some desired outputs. case (value1) This error message arises when you try to do operations on
MATLAB Commands matrices with different dimensions. For example A+B when A is
Live scripts: Contain MATLAB codes, embedded outputs, case (value2) 2 × 2 and B is 2 × 3.
formated texts, equations, and images together in a single MATLAB Commands
environment. end Subscript indices must either be real positive integers
or logicals.
* Add comment: To put a comment within a line, type % This error message arises because of indexing problem. For
followed by the comment in MATLAB command window, While loop statement: Repeat the commands while example A(1) is the first element in a matrix not A(0) (like
MATLAB script, or live script enviroment. condition holds. other programming languages).
Try, catch statement: try a statement, if it returns an true, NaN, inf, eye, rand, randi, and randn.
error, catch it and do another statement. ‘codistributed’: Access the arrays distributed among the
workers in a pool: zeros(5,5,‘codistributed’), etc.
try
statements GPU:
catch expression
statements gpuDevice(idx) Select GPU device specified by idx.
end
gpuArray(x) Copy x array to GPU.
arrayfun(func,A) Apply function to elements of A on GPU.
bsxfun(func,A,B) Apply an element-wise binary operation
error(‘msg’) Display message and abort function. plot(y) Plot y, with 1,2,3,... as the x axis.
specified by func to A and B on GPU.
warning(‘msg’) Display warning message. plot(x,f(x)) If f is a function, plot the points.
gather(A) Transfer gpuArray to local workspace.
assert(‘msg’) Throw error if condition is false. existsOnGPU(x) Determine if x is stored in GPU.
st=MException(ID... Input arguments:
,txt) Capture information of a specific
error and save it in the st object. A basic calculation on GPU: Line styles: { - / : / -. / -- }.
Markers: o : Circle / + : Plus sign / * : Asterisk
W=rand(5,‘single’); % Basic random numbers. / . : Point / x : Cross / s : Square
GD=gpuArray(W); % Send W to GPU. / d : Diamond / p : Pentagram / h :
GO=GD.*GD; % Execute multiplication on GPU. Hexagram / ^ : Upward triangle.
Parallel computing (CPU & GPU) Colors: y : Yellow / m : Magenta / c : Cyan
Plotting & Figures / r : Red / g : Green / b : Blue
CPU: / w : White / k : Black.
figure Open up a new figure window.
parpool(size) Create a new parallel pool (size is number of axis normal Default axis limits and scaling behavior.
CPU workers). Name-value pair arguments:
axis tight Force axis to be equaled to data range.
gcp Return the current parallel pool. axis equal Force axis to be scaled equally.
ticBytes/... Color Line color.
axis square Axis lines with equal lengths.
tocBytes(gcp) Start/stop calculation of the bytes transferred axis fill LineStyle Line style.
Lengths of each axis line fill the rectangle.
to the workers. LineWidth Line width.
title(‘Title’) Add a title at the top of the plot.
batch(‘scr’) Run a script or function on a worker. Marker Marker symbol.
xlabel(‘lbl’) Label the x axis as lbl.
gather(A) Transfer distributed array to local workspace. ylabel(‘lbl’) MarkerIndices Indices of marker data points.
Label the y axis as lbl.
MarkerEdgeColor Marker outline color.
zlabel(‘lbl’) Label the z axis as lbl.
MarkerFaceColor Marker fill color.
legend(‘v’,‘w’) Add label to v and w curves.
parfor: Replace for with parfor to execute code on CPU MarkerSize Size of marker.
grid on/off Include/Omit a grid in the plot.
workers or cores without any guaranteed order.
box on/off Display/hide the box outline around axes.
datetick(‘x’,fm) Date formatted tick labels (fm is format).
parfor i = a:s:b xtickformat(fm) X-axis label format.
MATLAB Commands ytickformat(fm) Y-axis label format.
end loglog(x,y) Logarithmic x and y axes.
xlim([min,max]) X-axis limits from min to max.
ylim([min,max]) Y-axis limits from min to max.
spmd: Execute code in parallel on workers of a pool. zlim([min,max]) Z-axis limits from min to max.
hold on/off Allow/prevent plotting on the same graph.
spmd text(x,y,text) Add text to a point (x and y are scalars
statements in data units).
spmd
fn is a function:
fplot(fn,rn) Plot a 2-D plot using fn over rn range.
parfeval: Directly execute a defined function on a specified fmesh(fn,rn) Plot a 3-D mesh using fn over rn range.
worker. fsurf(fn,rn) Plot a 3-D surface using fn over rn range.
fcontour(fn,rn) Plot contour using a function (fn) over semilogx(x,y) Logarithmic x axis.
rn range. semilogy(x,y) Logarithmic y axis.
p=gcp(); % Return current MATLAB pool.
f=parfeval(p,@sum,4,3); % Parallel execution of 4+3.
surf(x,y,z) 3-D shaded surface plot. polarhistogram(y) Histogram plot (polar coordi-
nates). bar(y) Bar plot.
mesh(x,y,z) 3-D mesh surface plot. scatter(x,y) 2-D scatter plot by x and y. bar3(y) 3-D bar plot.
histogram(y) Histogram plot. scatter(x,y,z) 3-D scatter plot by x, y, and z. pie(y)/pie3(y) 2-D/3-D pie plot.
compass(x) Compass plot (arrows from center). pointfig(y) Point and figure chart. Data science
Neural network
nnstart Neural network app (GUI).
patternnet(s,t,p) A pattern recognition (classification) network
with s, t, and p as number of hidden layers,
train, and performance function.
feedforwardnet(s,t) An approximation (regression) network with s
and t as number of hidden layers and train
function.
fitnet(s,t) Function fitting network with s and t as
number of hidden layers and train function.
boxplot(y) Box plot. dendrogram(tree) Dendrogram plot by tree.
cascade...
forwardnet(s,t) An approximation (regression) network with s
and t as number of hidden layers and train
function.
selforgmap Design a self-organizing map.
competlayer(nc) Design a competitive layer network with nc as
number of classes.
network Design a custom neural network with different
properties.
view(net) View a designed neural network.
train(net,i,o) Train a network using i and o as input and
output.