MATLAB Crash Course
Complete MATLAB crash course covering fundamentals, data types, matrices, operators, control flow, functions, and object-oriented programming — everything you need to go from zero to productive in MATLAB.
Linear Regression Explained: Single Variable and Multivariate Models with Gradient Descent
MATLAB Plotting & Visualization
MatLab (MATrix LABoratory)
MATLAB is a high-level language and interactive environment built for numerical computing, matrix operations, data analysis, visualization, and algorithm development.
It is widely used in engineering, research, AI/ML, signal processing, control systems, and finance.
Learning Path
- MATLAB On Ramp
- Deep Learning On Ramp
- Machine Learning on Ramp
- Reinforced Learning on Ramp
- Fundamentals of Programming
Install and Run
Follow instructions
brew install octave
octave --gui
Finding Help
doc fn— documentation for a function
%— add a comment
pwd— get current directorycd— change directoryls— list directorywho— view variables in current scopewhos— detailed view of variables in scopeclear— clear variables in current workspace
Data Types
Numeric Types
Integer and floating-point data:
- unsigned Int:
uint8/16/32/64 - signed Int:
int8/16/32/64 single— 4 byte floatdouble— 8 byte double precision
Characters and Strings
Text in character arrays and string arrays
Dates and Time
Arrays of date and time values that can be displayed in different formats
Categorical Arrays
Arrays of qualitative data with values from a finite set of discrete, nonnumeric data
Tables
Arrays in tabular form whose named columns can have different types
Structures
Arrays with named fields that can contain data of varying types and sizes
Cell Arrays
Arrays that can contain data of varying types and sizes
Function Handles
Variables that allow you to invoke a function indirectly
Variables
Precision
format long % up to 10+ decimal places
format short % up to 4 decimal places
Rules:
- Starts with alphabets
- Can contain a-z, A-Z, 0-9, and
_ - Can see data value by entering variable name
Saving & Loading
save <filename>.mat % save all variables
save <filename>.mat <varName> % save single variable
save <filename>.txt -ascii % save in readable format
load <filename>.mat % load all variables
load <filename>.mat <varName> % load single variable
clear % empty workspace
Creating Arrays & Matrices
magic(n,m) % sum of rows, columns, and diagonal is same
x = [7 9] % row array / row vector
x = x' % transpose into column vector
x = start:end % row vector [1,2,3,4]
x = start:step:end % row vector 1 to 5 step 0.5
x = (start:step:end)' % column vector
x = linspace(start, end, n) % equidistant row vector with n points
x = linspace(start, end, n)' % equidistant column vector with n points
,separates elements in the same row;separates rows
x = [7,9] % row array [element , element]
x = [7;9] % column array [element ; element]
x = [4,5 ; 7,9] % 2D matrix [ROW; ROW]
x = rand(n) % nxn matrix with random numbers
x = rand(n,m) % nxm matrix with random numbers
x = zeros(n,m) % nxm matrix of zeros
x = ones(n,m) % nxm matrix of ones
x = eye(n,m) % nxm matrix with 1s on the diagonal
x = eye(n) % nxn identity matrix
Trick:
A.*eye(n)= diagonal matrix of A
Reading Values from a Matrix
Indexing starts at 1.
length(V) % length of vector
size(A) % size of matrix
[dr, dc] = size(A) % size into dr, dc
[vMax, ivMax] = max(A) % max value and its index
A(:) % convert matrix into single column vector
A(i) % ith element of vector
A(n:m) % elements from index n to m
A(i,j) % ith row, jth column
A(end,j) % last row, j column
A(n, :) % all elements of nth row
A(:, n) % all elements of nth column
A(:, end-1:end) % all elements of last 2 columns
A([a,b], :) % all elements of rows a and b
Tricks
[vMax, ivMax] = max(A) % max value and its index
max(A,[],1) % max per column
max(A,[],2) % max per row
max(A(:)) % max element in A
sum(A,1) % per column sum
sum(A,2) % per row sum
sum(sum(A.*eye(n))) % sum of all diagonal elements of A
Update Values in a Matrix
A(i) = b % modify ith element to b
A(i,j) = b % modify (i,j) element to b
C = [A,B] % concatenate B after last column of A
C = [A;B] % concatenate B below last row of A
A = [A,[a;b;c]] % append column to A
Operations on a matrix apply to all elements:
A + b % add scalar b to all elements
A / b % divide all elements by scalar b
A < 3 % element-wise compare, returns binary matrix
[r,c] = find(A<3) % row and column indices satisfying condition
A + B % matrix addition
A.*B % element-wise multiplication
Built-in Functions
fn(A) % apply math fn to all elements (sqrt, abs, log, etc.)
sum(A) % sum of all elements
prod(A) % product of all elements
floor(A) % floor (0.5 → 0)
ceil(A) % ceiling (0.5 → 1)
Inverse
pinv(A) % pseudo-inverse of matrix
pinv(A)*A % identity matrix of A
Operators
Arithmetic Operators
+,-,*,/,^,()
Order of operations: () > ^ > *, / > +, -
A^n
Matrix power — repeated matrix multiplication (, n times). Only valid when A is square.
A.^n
Element-wise power — raises each element individually to the nth power. Works for any shape.
A.*B
Element-wise multiplication — multiplies corresponding elements.
Matrix Multiplication (A*B)
Given and , result is where .
Dot Product / Inner Product
RowVector(1×n) * ColumnVector(n×1) = Scalar
Outer Product
ColumnVector(n×1) * RowVector(1×n) = Matrix(n×n)
Right Divide (./)
A./B % divide each element of A by corresponding element of B
A./b % divide all elements of A by scalar b
Left Divide (.)
A.\B % divide each element of B by corresponding element of A
Relational Operators
<,>,<=,>=,==,~=
A > B % returns 1/0 array comparing each element of A with B
A > b % returns 1/0 array comparing each element with scalar b
Notes:
>,<,>=,<=— compare only the real part for complex numbers==,~=— test both real and imaginary partsInf == Infis true;NaN ~= NaNis true
Logical Operators
- Assert:
true,false - Logic:
|,&,~,xor - Short circuit:
||,&&
x = v1(v1<4 & v1>2) % all values of v1 between 2 and 4
L = logical(A) % converts A to logical array (0→false, nonzero→true)
Control Flow
If Else
if (condition)
...body
elseif (condition)
...body
else
...body
end
While
while (condition)
...body
continue % skip this step
break % exit loop
end
For Loop
for v = start:step:end
...body
continue % skip this step
break % exit loop
end
Switch Case
MATLAB executes only one case. Variables defined within a case are not available in other cases.
case_expressionmust be a scalar, character vector, or cell array of scalars/character vectorsswitch_expressionmust be a scalar or character vector
switch switch_expression
case case_expression
...body
case {case_expression1, case_expression2} % fall-through group
...body
otherwise
warning('Unexpected value.')
end
Try Catch
try
...body
catch ME
switch ME.identifier
case 'MATLAB:UndefinedFunction'
warning('Function is undefined. Assigning NaN.');
case 'MATLAB:scriptNotAFunction'
warning('Attempting to execute script as function.');
otherwise
rethrow(ME)
end
end
MATLAB allows nested
try/catchbut does not support multiplecatchblocks or afinallyblock.
Functions
Single Output
function out = fnName(param1, param2)
...body
end
Multiple Outputs
function [out1, out2] = fnName(param1, param2)
...body
end
Example:
function y = squareThisNumber(x)
y = x^2;
end
function [y1, y2] = squareAndCubeThisNumber(x)
y1 = x^2;
y2 = x^3;
end
Anonymous Function
Returns a single output. Can be passed as input to other functions. f is called a Function Handle.
f = @(params) expression
Object-Oriented Programming
Classes
A MATLAB class lives in its own file named after the class, starting with classdef.
% File: Point.m
classdef Point
properties
x
y
end
methods
function obj = Point(x, y) % constructor
obj.x = x;
obj.y = y;
end
function d = distanceFromOrigin(obj)
d = sqrt(obj.x^2 + obj.y^2);
end
end
end
Usage:
p = Point(3, 4);
p.distanceFromOrigin() % 5
Properties
Hold the state/data of an object — equivalent to fields in other OOP languages.
properties
x
y = 0 % default value
end
properties (Access = private)
secret % only accessible inside the class
end
Methods
Functions that operate on an object's properties. The first argument is conventionally obj.
methods
function obj = setX(obj, newX)
obj.x = newX; % MATLAB objects are value types — must return obj
end
end
Constructor
A method with the same name as the class, called automatically on instantiation. If omitted, MATLAB provides a default no-argument constructor.
Inheritance
A subclass extends a base class using < BaseClassName.
classdef Point3D < Point
properties
z
end
methods
function obj = Point3D(x, y, z)
obj = obj@Point(x, y); % call superclass constructor
obj.z = z;
end
function d = distanceFromOrigin(obj)
d = sqrt(obj.x^2 + obj.y^2 + obj.z^2); % overrides parent method
end
end
end
Encapsulation
Restrict access to internal state using Access attributes.
properties (Access = private)
balance = 0
end
methods
function obj = deposit(obj, amount)
obj.balance = obj.balance + amount;
end
function b = getBalance(obj)
b = obj.balance;
end
end
