MATLAB, a programming language for technical computing, is a powerful tool that can perform all sorts of math tasks in an engineering or scientific environment. It's incredibly flexible, with an extensive array of functions that you can use to meet specific needs in your environment.

Using such a complex environment can prove daunting at first, but this Cheat Sheet can help: Learn common MATLAB commands; become familiar with standard operators and precedence and learn to recognize line plot styles.

The Ultimate Ticket to Top Data Science Job Roles

Post Graduate Program In Data ScienceExplore Now
The Ultimate Ticket to Top Data Science Job Roles

Matlab Basics

Workspace

ans %Most recent answer 

clc %clear command window 

clear var %clear variables Workspace 

clf %Clear all plots 

close all %Close all plots 

ctrl-c %Kill the current calculation 

doc fun %open documentation 

disp(’text’) %Print text 

format short—long %Set output display format 

help fun %open in-line help 

load filename {vars} %load variables from .mat file 

save {-append} file {vars} %save var to file 

addpath path %include path to .. 

iskeyword arg %Check if arg is keyword % This is a comment Comments 

... %connect lines (with break) 

";" (after command) %suppresses output 

scriptname %runs scriptname.m 

tic, toc %start and stop timer 

ver %List of installed toolboxes

Defining and Changing Variables

myVariable = 4  % Notice Workspace pane shows newly created variable

myVariable = 4; % Semi colon suppresses output to the Command Window

4 + 6       % ans = 10

8 * myVariable  % ans = 32

2 ^ 3       % ans = 8

a = 2; b = 3;

c = exp(a)*sin(pi/2) % c = 7.3891

% Logicals

1 > 5 % ans = 0

10 >= 10 % ans = 1

3 ~= 4 % Not equal to -> ans = 1

3 == 3 % equal to -> ans = 1

3 > 1 && 4 > 1 % AND -> ans = 1

3 > 1 || 4 > 1 % OR -> ans = 1

~1 % NOT -> ans = 0

% Logicals can be applied to matrices:

A > 5

% for each element, if condition is true, that element is 1 in returned matrix

A( A > 5 )

% returns a vector containing the elements in A for which condition is true

% Strings

a = 'MyString'

length(a) % ans = 8

a(2) % ans = y

[a,a] % ans = MyStringMyString

% Cells

a = {'one', 'two', 'three'}

a(1) % ans = 'one' - returns a cell

char(a(1)) % ans = one - returns a string

% Structures

A.b = {'one','two'};

A.c = [1 2];

A.d.e = false;

% Variables can be saved to .mat files

save('myFileName.mat') % Save the variables in your Workspace

load('myFileName.mat') % Load saved variables into Workspace

Become a Data Scientist With Real-World Experience

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist With Real-World Experience

Arithmetics

transpose(A) % Transpose the matrix, which is the same as:

A one

A' % Concise version of complex transpose

A.' % Concise version of transpose (without taking complex conjugate)

size(A) % ans = 3 3

% Element by Element Arithmetic vs. Matrix Arithmetic

% On their own, the arithmetic operators act on whole matrices. When preceded

% by a period, they act on each element instead. For example:

A * B % Matrix multiplication

A .* B % Multiple each element in A by its corresponding element in B

% There are several pairs of functions, where one acts on each element, and

% the other (whose name ends in m) acts on the whole matrix.

exp(A) % exponentiate each element

expm(A) % calculate the matrix exponential

sqrt(A) % take the square root of each element

sqrtm(A) %  find the matrix whose square is A

% Solving matrix equations (if no solution, returns a least squares solution)

% The \ and / operators are equivalent to the functions mldivide and mrdivide

x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b.

x=b/A % Solves xA=b

inv(A) % calculate the inverse matrix

pinv(A) % calculate the pseudo-inverse

% Common matrix functions

zeros(m,n) % m x n matrix of 0's

ones(m,n) % m x n matrix of 1's

diag(A) % Extracts the diagonal elements of a matrix A

diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere

eye(m,n) % Identity matrix

linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2

inv(A) % Inverse of matrix A

det(A) % Determinant of A

eig(A) % Eigenvalues and eigenvectors of A

trace(A) % Trace of matrix - equivalent to sum(diag(A))

isempty(A) % Tests if array is empty

all(A) % Tests if all elements are nonzero or true

any(A) % Tests if any elements are nonzero or true

isequal(A, B) % Tests equality of two arrays

numel(A) % Number of elements in matrix

triu(x) % Returns the upper triangular part of x

tril(x) % Returns the lower triangular part of x

cross(A,B) %  Returns the cross product of the vectors A and B

dot(A,B) % Returns scalar product of two vectors (must have the same length)

transpose(A) % Returns the transpose of A

fliplr(A) % Flip matrix left to right

flipud(A) % Flip matrix up to down

% Matrix Factorisations

[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix

[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues

[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order

[Q, R] = qr(A) % if A is mxn, Q is mxm and R is mxn upper triangular

% Common vector functions

max     % largest component

min     % smallest component

length  % length of a vector

sort    % sort in ascending order

sum     % sum of elements

prod    % product of elements

mode    % modal value

median  % median value

mean    % mean value

std     % standard deviation

perms(x) % list all permutations of elements of x

find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, 

        % i.e. find( x == 3 ) returns indexes of elements that are equal to 3

        % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3

Become a Data Scientist With Real-World Experience

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist With Real-World Experience

Elementary Functions

sin(x)

cos(x)

tan(x)

asin(x)

acos(x)

atan(x)

exp(x)

sqrt(x)

log(x)

log10(x)

abs(x) %If x is complex, returns magnitude

min(x)

max(x)

ceil(x)

floor(x)

round(x)

rem(x)

rand % Uniformly distributed pseudorandom numbers

randi % Uniformly distributed pseudorandom integers

randn % Normally distributed pseudorandom numbers

%Complex math operations

abs(x)   % Magnitude of complex variable x

phase(x) % Phase (or angle) of complex variable x

real(x)  % Returns the real part of x (i.e returns a if x = a +jb)

imag(x)  % Returns the imaginary part of x (i.e returns b if x = a+jb)

conj(x)  % Returns the complex conjugate 

% Common constants

pi

NaN

inf

% Given a meshgrid X,Y and a function defined on the meshgrid like Gauss, interpolates the value of the function at the point u1,u2

interp2(X,Y,Gauss,u1,u2)

Complex Numbers

abs(z) %Absolute value and complex magnitude 

angle(z) %Phase angle 

complex(a,b) %Create complex numbers 

conj(z) %Elementwise complex conjugate i or j Imaginary unit 

imag(z) %Imaginary part of complex number 

isreal(z) %Determine whether array is real 

real(z) %Real part of complex number 

ctranspose(Z) %Complex conjugate transpose

Constants

pi %π = 3.141592653589793 

NaN %Not a number (i.e. 0/0) 

Inf %Infinity 

eps %Floating-point relative accuracy 

realmax %Largest positive floating-point number 

realmin %Smallest positive floating-point number

Keyboard Shortcuts

Numbers and Linear Algebra

A’ %Transpose of matrix or vector 

inv(A) %inverse of A (use with care!) 

det(A) %determinant of A 

eig(A),eigs(A) %eigenvalues of A (subset) 

cross(A,B) %Cross product 

dot(A,B) %Dot product 

kron(A,B) %Kronecker tensor product 

norm(x) %Vector and matrix norms 

linsolve(A,B) %Solve linear system of equations 

rank(A) %Rank of matrix 

trace(A) %Sum of diagonal elements 

curl(X,Y,Z,U,V,W) %Curl and angular velocity 

divergence(X,..,W) %Compute divergence of vector field 

null(A) %Null space of matrix 

orth(A) %Orthonormal basis for matrix range 

mldivide(A,B) %Solve linear system Ax = B for x 

mrdivide(B,A) %Solve linear system xA = B for x 

decomposition(A) %Matrix decomposition 

lsqminnorm(A,B) %Least-squares solution to linear eq. 

rref(A) %Reduced row echelon form 

balance(A) %Diagonal scaling (improve eig. vec.) 

svd(A) %Singular value decomposition 

gsvd(A,B) %Generalized svd 

chol(A) %Cholesky factorization

Numerical Integration and Differentiation

integral(f,a,b) %Numerical integration 

integral2(f,a,b,c,d) %2D num. integration 

integral3(f,a,b,..,r,s) %3D num. integration 

trapz(x,y) %Trapezoidal integration 

cumtrapz(x,y) %Cumulative trapez integration 

diff(X) %Differences (along columns) 

gradient(X) %Numerical gradient

Become a Data Scientist With Real-World Experience

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist With Real-World Experience

Matrix Functions/ Linear Algebra

zeros(m,n) % m x n matrix of 0's

ones(m,n) % m x n matrix of 1's

diag(A) % Extracts the diagonal elements of a matrix A

diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere

eye(m,n) % Identity matrix

linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2

inv(A) % Inverse of matrix A

det(A) % Determinant of A

eig(A) % Eigenvalues and eigenvectors of A

trace(A) % Trace of matrix - equivalent to sum(diag(A))

isempty(A) % Tests if array is empty

all(A) % Tests if all elements are nonzero or true

any(A) % Tests if any elements are nonzero or true

isequal(A, B) % Tests equality of two arrays

numel(A) % Number of elements in matrix

triu(x) % Returns the upper triangular part of x

tril(x) % Returns the lower triangular part of x

cross(A,B) %  Returns the cross product of the vectors A and B

dot(A,B) % Returns scalar product of two vectors (must have the same length)

transpose(A) % Returns the transpose of A

fliplr(A) % Flip matrix left to right

flipud(A) % Flip matrix up to down

Matrix Manipulation

A(2:3,2:3) % Creates a new matrix from the old one

%ans =

%     5     42

%     8     9

A(:,1) % All rows in column 1

%ans =

%     1

%     4

%     7

A(1,:) % All columns in row 1

%ans =

%     1     2     3

[A ; A] % Concatenation of matrices (vertically)

%ans =

%     1     2     3

%     4     5    42

%     7     8     9

%     1     2     3

%     4     5    42

%     7     8     9

% this is the same as

vertcat(A,A);

[A , A] % Concatenation of matrices (horizontally)

%ans =

%     1     2     3     1     2     3

%     4     5    42     4     5    42

%     7     8     9     7     8     9

% this is the same as

horzcat(A,A);

A(:, [3 1 2]) % Rearrange the columns of original matrix

%ans =

%     3     1     2

%    42     4     5

%     9     7     8

A(1, :) =[] % Delete the first row of the matrix

A(:, 1) =[] % Delete the first column of the matrix

squeeze(A); % Removes singular dimensions ie. 2x1x3 -> 2x3

Get In-Demand Skills to Launch Your Data Career

Big Data Hadoop Certification Training CourseExplore Course
Get In-Demand Skills to Launch Your Data Career

Graphics

Plotting

x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1

y = sin(x);

plot(x,y)

xlabel('x axis')

ylabel('y axis')

title('Plot of y = sin(x)')

axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1

plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot

legend('Line 1 label', 'Line 2 label') % Label curves with a legend

% Alternative method to plot multiple functions in one plot.

% while 'hold' is on, commands add to existing graph rather than replacing it

plot(x, y)

hold on

plot(x, z)

hold off

loglog(x, y) % A log-log plot

semilogx(x, y) % A plot with logarithmic x-axis

semilogy(x, y) % A plot with logarithmic y-axis

fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5

% Creates a meshgrid (2D grid) to calculate a function for every point in the grid

[X, Y] = meshgrid(x_min:step:x_max, y_min:step:y_max)

grid on % Show grid; turn off with 'grid off'

axis square % Makes the current axes region square

axis equal % Set aspect ratio so data units are the same in every direction

scatter(x, y); % Scatter-plot

hist(x); % Histogram

stem(x); % Plot values as stems, useful for displaying discrete data

bar(x); % Plot bar graph

z = sin(x);

plot3(x,y,z); % 3D line plot

pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value

contour(A) % Contour plot of matrix

contourf(A) % Filled contour plot of matrix

mesh(A) % Plot as a mesh surface

h = figure % Create new figure object, with handle h

figure(h) % Makes the figure corresponding to handle h the current figure

close(h) % close figure with handle h

close all % close all open figure windows

close % close current figure window

shg % bring an existing graphics window forward, or create new one if needed

clf clear % clear current figure window, and reset most figure properties

% Properties can be set and changed through a figure handle.

% You can save a handle to a figure when you create it.

% The function get returns a handle to the current figure

h = plot(x, y); % you can save a handle to a figure when you create it

set(h, 'Color', 'r')

% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black

set(h, 'LineStyle', '--')

 % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line

get(h, 'LineStyle')

% The function gca returns a handle to the axes for the current figure

set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis

% To create a figure that contains several axes in tiled positions, use subplot

subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots

plot(x1); title('First Plot') % plot something in this position

subplot(2,3,2); % select second position in the grid

plot(x2); title('Second Plot') % plot something there

% Given

x1 = [-3:0.5:3];

x2 = x1;

y = randi(500, length(x1), length(x1));

% Show a 3-D plot

figure

subplot(2,1,1);

surf(x1,x2,y);

xlabel(’x_1’);

ylabel(’x_2’);

% Show contours

subplot(2,1,2);

contour(x1,x2,y);

xlabel(’x_{1}’);

ylabel(’x_{2}’);

axis equal

% Show a colour map

figure

imagesc(x1,x2,y)

xlabel(’x_{1}’);

ylabel(’x_{2}’);

Become a Data Scientist With Real-World Experience

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist With Real-World Experience

Plot Types

  1. Plot
  2. Plot3
  3. Stairs
  4. Errorbar
  5. Stackedplot
  6. Loglog
  7. Semilogs
  8. Semilogy
  9. Polarplot
  10. Contour
  11. Quiver
  12. Quiver3
  13. Histogram
  14. Pie
  15. Scatter
  16. Scatterhist
  17. Plotmatrix
  18. Heatmap

Programming Methods

Functions

load('myFile.mat', 'y')

% Command syntax:

load myFile.mat y   % no parentheses, and spaces instead of commas

% Calling a function from a script

% [arguments out] = function_name(arguments in)

[V,D] = eig(A);

[~,D] = eig(A);  % if you only want D and not V

% To use functions or scripts, they must be on your path or current directory

path % displays current path

addpath /path/to/dir % add to path

rmpath /path/to/dir % remove from path

cd /path/to/move/into % change directory

% M-file Scripts

% Have .m extensions

% M-file Functions

% 'help double_input.m' returns the comments under line beginning function

function output = double_input(x)

    %double_input(x) returns twice the value of x

    output = 2*x;

end

double_input(6) % ans = 12

% Example that returns the square of it's input, assigned to the handle sqr:

sqr = @(x) x.^2;

sqr(10) % ans = 100

doc function_handle % find out more

Anonymous Functions

% defined via function handles 

f = @(x) cos(x.ˆ2)./(3*x);

Relational and Logical Operations

== %Check equality 

∼= %Check inequality 

> %greater than 

>= %greater or equal to 

< %less than 

<= %less or equal to 

&, && %logical AND 

∼ %logical NOT 

|, | | %logical OR 

xor %logical exclusive-OR

if, elseif Conditions

if (a > 15)

    disp('Greater than 15')

elseif (a == 23)

    disp('a is 23')

else

    disp('neither condition met')

end

Switch Case

n = input('Enter a number: '); 

switch n 

case -1 

disp('negative one') 

case 0 

disp('zero') 

case {1,2,3} %check three cases together 

disp('positive one') 

otherwise 

disp('other value') 

end % control structures terminate with end

For-Loop

for k = 1:5

    disp(k)

end

While-Loop

k = 0;

while (k < 5)

    k = k + 1;

end

Become a Data Scientist With Real-World Experience

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist With Real-World Experience

Special Topics

Polynomials

poly(x) %Polynomial with roots x 

poly(A) %Characteristic polynomial of matrix 

polyeig(x) %Polynomial eigenvalue problem 

polyfit(x,y,d) %Polynomial curve fitting 

residue(b,a) %Partial fraction expansion/decomposition 

roots(x) %Polynomial roots 

polyval(p,x) %Evaluate poly p at points x 

conv(u,v) %Convolution and polynomial multiplication 

deconv(u,v) %Deconvolution and polynomial division 

polyint(p,k) %Polynomial integration 

polyder(p) %Polynomial differentiation

Interpolation and Fitting

interp1(x,v,xq) %1-D data interpolation (table lookup) 

interp2(X,Y,V,Xq,Yq) %2D interpolation for meshgrid data 

interp3(X,..V,..Zq) %3D interpolation for meshgrid data 

pchip(x,v,xq) %Piece. cubic Hermite poly interpol 

spline(x,v,xq) %Cubic spline data interpolation 

ppval(pp,xq) %Evaluate piecewise polynomial 

mkpp(breaks,coeffs) %Make piecewise polynomial 

unmkpp(pp) %Extract piecewise polynomial details

Differential Equations

ode45(ode,tspan,y0) %Solve system of nonstiff ODE 

ode15s(ode,tspan,y0) %Solve system of stiff ODE 

pdepe(m,pde,ic,bc,xm,ts) %Solve 1D PDEs 

pdeval(m,xmesh,usol,xq) %Interpolate num. PDE solution

Optimization

fminbnd(fun,x1,x2) %Find minimum of fun(x) in [x1, x2] 

fminsearch(fun,x0) %Find minimum of function 

lsqnonneg(C,d) %Solve non-neg. lin. least-squares prob. 

fzero(fun,x0) %Root of nonlinear function 

optimget(opt,’par’) %Optimization options values 

optimset(’opt’,val) %Define optimization options

Descriptive Statistics

bounds(A) %Smallest and largest elements 

max(A) %Maximum elements of an array 

min(A) %Minimum elements of an array 

mode(A) %Most frequent values in array 

mean(A) %Average or mean value of array 

median(A) %Median value of array 

std(A) %Standard deviation 

var(A) %Variance 

hist(X) %calculate and plot histogram 

corrcoef(A) %Correlation coefficients 

cov(A) %Covariance 

xcorr(x,y) %Cross-correlation 

xcov(x,y) %Cross-covariance 

rand %Uniformly distributed random numbers 

randn %Normally distributed random numbers 

randi %Uniformly distributed pseudorandom integers

Discrete Math

factor(n) %Prime factors 

factorial(n) %Factorial of input 

gcd(n,m) %Greatest common divisor 

lcm(n,m) %least common multiple 

mod(a,m) %Remainder after division (modulo operation) 

ceil(X) %Round toward positive infinity 

fix(X) %Round toward zero 

floor(X) %Round toward negative infinity 

round(X) %Round to nearest decimal or integer

MATLAB as a Programming Language 

MATLAB is a high-level language and interactive environment for numerical computation, visualization, and programming. MATLAB supports the entire range of engineering and science applications, including control, signal processing, communications, data analysis, optimization, and system modeling. 

A single toolbox handles virtually all computational tasks in engineering and scientific research.

Learn over a dozen of data science tools and skills with Professional Certificate Program in Data Science and get access to masterclasses by Purdue faculty. Enroll now and add a shining star to your data science resume!

Conclusion

Learning MATLAB will help you become a data scientist. Data science is one of the most lucrative fields to enter today. And it's only going to get bigger.

In order to be successful in this industry, you need to know MATLAB and other programming languages like Python and R. You'll also need some practical experience applying data science techniques to solve real-world problems.

Simplilearn's Professional Certificate Program in Data Science will help you master MATLAB and other programming languages like Python and R. You'll also learn how to apply data science techniques to solve real-world problems.

The course covers various topics in depth and has a lot of practical components for getting you job-ready from day one.

Data Science & Business Analytics Courses Duration and Fees

Data Science & Business Analytics programs typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Post Graduate Program in Data Analytics

Cohort Starts: 6 May, 2024

8 Months$ 3,749
Data Analytics Bootcamp

Cohort Starts: 7 May, 2024

6 Months$ 8,500
Caltech Post Graduate Program in Data Science

Cohort Starts: 9 May, 2024

11 Months$ 4,500
Applied AI & Data Science

Cohort Starts: 14 May, 2024

3 Months$ 2,624
Post Graduate Program in Data Science

Cohort Starts: 28 May, 2024

11 Months$ 4,199
Data Scientist11 Months$ 1,449
Data Analyst11 Months$ 1,449