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 .m files.

    • 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.

MATLAB desktop environment showing Editor, Command Window, Workspace, and Current Directory
  • 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 for help; 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 6363 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-bit char, single precision, integers (uint8, uint16), logicals, and complex numbers.

    • Reserved constants: pi (π\pi), i and j (−1\sqrt{-1}), Inf (∞\infty), NaN (not-a-number), ans (default variable for unassigned outputs).

  • Array Construction:

    • Row vectors: Commas or spaces separate elements (e.g., [1, 2, 5.4][1\text{, } 2\text{, } 5.4]).

    • Column vectors: Semicolons separate rows (e.g., [4; 2; 7][4\text{; } 2\text{; } 7]).

    • Matrices: Formed by combining row and column delimiters (e.g., [1, 2; 3, 4][1\text{, } 2\text{; } 3\text{, } 4]).

    • Automatic initialization routines: linspace(start, stop, n), logspace(a, b, n), colon indexing start:step:stop, zeros(m, n), ones(m, n), eye(n), rand(m, n) (uniform on [0,1][0, 1]), and randn(m, n) (standard normal distribution N(0,1)N(0, 1)).

  • Array Dimensions:

    • size(A) returns a vector of dimensions [m, n][m\text{, } n].

    • length(v) returns max⁡(m,n)\max(m, n).

    • numel(A) returns total count of elements (m×nm \times n).

  • 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 .m files where the primary function name matches the file name; defined via function [out1, out2] = funName(in1, in2); execute within an isolated local workspace.

    • Functions support overloading with variable inputs/outputs via nargin and nargout.

    • 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 ... end iterates over column elements of the given vector.

    • Conditional loops: while condition ... end executes as long as the scalar expression remains true; loops can be exited immediately using break.

  • Performance Optimization:

    • Vectorization: Replaces iterative for loops with built-in array operations and index mapping (such as find(condition) or logical indexing A(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 tic and toc; execution auditing via profile 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 braces C{i, j} read or assign the underlying data content.

Structure of a 3x3 cell array containing mixed data types
  • Structures (struct):

    • Multi-field containers organizing data by named attributes accessed via dot notation: s.fieldName.

    • Initialized via s = struct or structured field-value array definitions: struct('field1', {val1, val2}).

  • File Input and Output:

    • Native workspace files: save('filename.mat') and load('filename.mat').

    • Delimited text: importdata('file.txt', delimiter), textscan(), fscanf().

    • Spreadsheets: xlsread('file.xlsx') and xlswrite('file.xlsx', data).

    • Low-level binary/stream I/O: fopen(), fread(), fwrite(), fseek(), and fclose().

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 using set(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 corresponding colormap (such as parula, jet, gray) and colorbar.

    • 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: Ax=bA\mathbf{x} = \mathbf{b}.

    • Solver: Left matrix division operator x = A \ b directly computes exact solutions for square non-singular matrices and least-squares solutions for rectangular systems.

    • Matrix properties: rank(A), determinant det(A), condition number cond(A) / rcond(A), matrix inverse inv(A).

    • Factorizations: Eigenvalue decomposition eig(), singular value decomposition svd(), QR factorization qr(), LU factorization lu(), Cholesky factorization chol().

  • Polynomial Operations:

    • Polynomials are encoded as row vectors of descending degree coefficients: P=[an, an−1, …, a0]P = [a_n\text{, } a_{n-1}\text{, } \dots\text{, } a_0].

    • 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 NthN^{\text{th}}-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 x0x_0.

    • 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: @odefun accepts scalar time t and state vector y, returning column vector dydt\frac{d\mathbf{y}}{dt}.

    • Solver variants: ode45 (standard explicit Runge-Kutta 4th/5th4^{\text{th}}/5^{\text{th}} 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.

Simulink block diagram model for a bouncing ball with a second-order integrator
  • Symbolic Math Toolbox:

    • Executes exact analytical algebra and calculus without floating-point truncation.

    • Variables defined with syms x y or sym('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) or fspecial('motion', len, theta), convolution with imfilter(), and restoration via deconvblind().

    • Feature detection: Edge discovery using edge(I, 'sobel') or edge(I, 'canny'); circle detection using imfindcircles().

  • Hardware Interfacing:

    • Low-level serial communication: s = serial('COM3'), configured and managed via fopen(s), fprintf(s, ...), fscanf(s), and fclose(s).

    • Instrument automation: General Purpose Interface Bus protocol using gpib().