Comprehensive MATLAB Foundations, Programming, and Scientific Computing Notes
MATLAB Environment and Syntax Fundamentals
Platform Architecture: High-level, interactive technical computing environment optimized for matrix and vector computations; executes as an interpreted language line-by-line.
Desktop Interface Elements:
Command Window: Direct line-by-line command execution at the
>>prompt.Editor: Code creation, section execution, and debugging for script and function
.mfiles.Workspace: Variable browser tracking active identifiers, dimensions, byte allocations, and data types (
who,whos,clear).Current Folder / Directory: Active working directory managing file dependencies and search paths.

Syntax and Punctuation Conventions:
Semicolon (
;): Suppresses command output in the command window; separates rows within matrix declarations; allows multiple commands on a single line.Comma (
,): Separates function arguments and horizontal array elements; permits multiple commands per line while preserving output display.Percent sign (
%): Designates comments; contiguous comments at file starts serve as documentation forhelp; double percent signs (%%) demarcate code sections.Ellipsis (
...): Extends a continuous code statement onto the next line.Exclamation point (
!) /system(): Issues commands directly to the underlying host operating system terminal.
Variables, Arrays, and Matrix Operations
Typing and Identifier Rules:
Weakly typed language requiring no explicit variable pre-allocation or data type declaration.
Variable names must begin with a letter, are case-sensitive, support up to characters, and allow alphanumeric characters and underscores.
Default data type is the 64-bit double-precision floating-point number (
double); other core types include 16-bitchar, single precision, integers (uint8,uint16), logicals, and complex numbers.Reserved constants:
pi(),iandj(),Inf(),NaN(not-a-number),ans(default variable for unassigned outputs).
Array Construction:
Row vectors: Commas or spaces separate elements (e.g.,
).Column vectors: Semicolons separate rows (e.g.,
).Matrices: Formed by combining row and column delimiters (e.g.,
).Automatic initialization routines:
linspace(start, stop, n),logspace(a, b, n), colon indexingstart:step:stop,zeros(m, n),ones(m, n),eye(n),rand(m, n)(uniform on ), andrandn(m, n)(standard normal distribution ).
Array Dimensions:
size(A)returns a vector of dimensions.length(v)returns .numel(A)returns total count of elements ().
Matrix vs. Element-Wise Operations:
Matrix operations conform to linear algebra rules: matrix multiplication
*, matrix power^(square matrices only), transpose'(complex conjugate transpose), and non-conjugate transpose.'.Element-wise operations require a period prefix before the operator:
.*,./,.\,.^.
Programming: Scripts, Functions, and Control Flow
Scripts vs. Functions:
Scripts: Sequential commands executing within the global/base workspace; do not accept explicit inputs or return outputs.
Functions: Stored in
.mfiles where the primary function name matches the file name; defined viafunction [out1, out2] = funName(in1, in2); execute within an isolated local workspace.Functions support overloading with variable inputs/outputs via
narginandnargout.Anonymous functions construct inline function handles without dedicated files using
@(args) expression.
Relational and Logical Operators:
Relational:
==(equal),~=(not equal),<,>,<=,>=.Logical: element-wise
&(AND),|(OR),~(NOT),xor(),all(),any(); short-circuit scalar evaluations use&&and||.
Flow Control Constructs:
Branching:
if condition ... elseif condition ... else ... end; multiple branches evaluate sequentially.Fixed loops:
for var = vector ... enditerates over column elements of the given vector.Conditional loops:
while condition ... endexecutes as long as the scalar expression remains true; loops can be exited immediately usingbreak.
Performance Optimization:
Vectorization: Replaces iterative
forloops with built-in array operations and index mapping (such asfind(condition)or logical indexingA(A > 0)).Memory Preallocation: Defines output array dimensions prior to loops (e.g.,
A = zeros(m, n)) to prevent repetitive dynamic resizing.Diagnostic profiling: Benchmarking with
ticandtoc; execution auditing viaprofile on,profile viewer.
Data Structures: Cells, Structures, and File I/O
Cell Arrays:
Heterogeneous arrays holding elements of varying sizes, dimensions, and data types.
Parentheses
C(i, j)access the cell container; curly bracesC{i, j}read or assign the underlying data content.

Structures (
struct):Multi-field containers organizing data by named attributes accessed via dot notation:
s.fieldName.Initialized via
s = structor structured field-value array definitions:struct('field1', {val1, val2}).
File Input and Output:
Native workspace files:
save('filename.mat')andload('filename.mat').Delimited text:
importdata('file.txt', delimiter),textscan(),fscanf().Spreadsheets:
xlsread('file.xlsx')andxlswrite('file.xlsx', data).Low-level binary/stream I/O:
fopen(),fread(),fwrite(),fseek(), andfclose().
2D and 3D Visualization Techniques
2D Coordinate Plotting:
plot(x, y)draws linear line connections between ordered pairs; handles multiple pairs:plot(x1, y1, x2, y2).Formatting options specified via compact strings
'[color][marker][linestyle]'(e.g.,'r--s') or key-value parameters ('LineWidth','MarkerFaceColor').Plot enhancements:
xlabel(),ylabel(),title(),legend(),grid on.Semi-log and log-log plots:
semilogx(),semilogy(),loglog().Subplots:
subplot(rows, cols, index)tiles multiple axes inside a single figure window.
Figure and Handle Graphics:
Visual elements maintain addressable handles: current figure (
gcf), current axes (gca), line object (h = plot(...)).Properties inspected using
get(h)and modified usingset(h, 'Property', value).
3D Visualizations and Matrix Surfaces:
plot3(x, y, z)renders 3D line trajectories.imagesc(C)visualizes 2D matrices as scaled color images with a correspondingcolormap(such asparula,jet,gray) andcolorbar.Grid generation:
[X, Y] = meshgrid(x, y)transforms 1D coordinate vectors into 2D evaluation grids.Surface plots:
surf(X, Y, Z)plots shaded 3D polygonal meshes with shading styles (faceted,flat,interp).Contour plots:
contour(X, Y, Z, levels)generates 2D isoline curves;contourf()creates filled isolines.
Linear Algebra, Polynomials, and Optimization
Systems of Linear Equations:
Linear system representation:
.Solver: Left matrix division operator
x = A \ bdirectly computes exact solutions for square non-singular matrices and least-squares solutions for rectangular systems.Matrix properties:
rank(A), determinantdet(A), condition numbercond(A)/rcond(A), matrix inverseinv(A).Factorizations: Eigenvalue decomposition
eig(), singular value decompositionsvd(), QR factorizationqr(), LU factorizationlu(), Cholesky factorizationchol().
Polynomial Operations:
Polynomials are encoded as row vectors of descending degree coefficients:
.Evaluation:
polyval(P, x)calculates polynomial values across scalar or array inputs.Roots:
roots(P)extracts all roots;poly(r)computes the coefficient vector from given roots.Curve fitting:
polyfit(x, y, N)fits an -order least-squares polynomial to discrete data coordinates.
Optimization and Root Finding:
Non-linear zero-finding:
fzero(fun, x0)finds roots of single-variable functions near.1D bounded minimization:
fminbnd(fun, x_1, x_2)identifies local minima within specified bounds.Multivariable unconstrained optimization:
fminsearch(fun, x0)applies the simplex search method.
Numerical Calculus and Differential Equations
Numerical Differentiation and Integration:
Discrete differences:
diff(y) ./ diff(x)approximates derivatives;gradient(M)evaluates multidimensional central differences.Numerical quadrature:
trapz(x, y)computes trapezoidal integration over discrete arrays;quad(fun, a, b)applies adaptive Simpson's quadrature to function handles.
Ordinary Differential Equations (ODEs):
Standard solver interface:
[t, y] = ode45(@odefun, [t0, tf], y0).State derivative function:
@odefunaccepts scalar timetand state vectory, returning column vector.Solver variants:
ode45(standard explicit Runge-Kutta order),ode23(lower-order non-stiff),ode15s(variable-order solver for stiff equations).Higher-order ODE reduction: Higher-order differential equations are reduced to a system of coupled first-order equations by defining intermediate state variables.
Solver options: Adjusted via
odeset('RelTol', 1e-6, 'AbsTol', 1e-10).
Toolboxes: Simulink, Symbolic Math, Image Processing, and Hardware
Simulink Modeling Environment:
Graphical, block-diagram programming environment for time-domain simulation of continuous, discrete, and hybrid physical systems.
Core block libraries: Sources (inputs, signal generators), Sinks (Scopes, workspace loggers), Continuous (Integrators, State-Space), Math Operations.

Symbolic Math Toolbox:
Executes exact analytical algebra and calculus without floating-point truncation.
Variables defined with
syms x yorsym('1/3').Expressions: Manipulated using
expand(),factor(),simplify(),collect(),pretty().Substitution and Calculus:
subs(expr, var, val)replaces variables;diff(expr)differentiates analytically;int(expr, a, b)computes analytical integrals;solve(eqn, var)solves algebraic equations symbolically.
Image Processing Toolbox:
I/O and display:
imread(),imwrite(),imshow(),imresize().Contrast and histogram adjustments:
imadjust()(intensity clipping and scaling),histeq()(histogram equalization),adapthisteq()(adaptive histogram equalization).Spatial filtering: Kernel definition with
fspecial('disk', r)orfspecial('motion', len, theta), convolution withimfilter(), and restoration viadeconvblind().Feature detection: Edge discovery using
edge(I, 'sobel')oredge(I, 'canny'); circle detection usingimfindcircles().
Hardware Interfacing:
Low-level serial communication:
s = serial('COM3'), configured and managed viafopen(s),fprintf(s, ...),fscanf(s), andfclose(s).Instrument automation: General Purpose Interface Bus protocol using
gpib().