📐 MATLAB Core Paradigm

🎯 Matrix Laboratory DNA

MATLAB (MathWorks, 1984) is a high-performance language for technical computing integrating computation, visualization, and programming. Everything is a double-precision array by default. Interactive environment, JIT compilation, built-in linear algebra (BLAS/LAPACK), and extensive toolboxes. Core principles: vectorization, array-oriented syntax, and interpreter with just-in-time acceleration.

Deep Explanation

MATLAB's first-class citizen: matrices. Variables are dynamically typed, but default numeric type is double. The language uses 'column-major' storage (Fortran order). Built-in operators are highly optimized for matrix algebra. The workspace is interactive; M-files combine scripts and functions. Unlike Python lists, MATLAB matrices enforce homogeneity and offer blazing-fast linear algebra.

Why it matters: Mastering MATLAB's array-centric thinking reduces code by 10x compared to loops. Leverage LAPACK for eigenvalue decomposition, SVD, and QR factorization directly.

📌 1-indexing📌 Column-major order📌 JIT compilation📌 Interactive REPL
% MATLAB Core: matrices everywhere A = [1 2 3; 4 5 6; 7 8 9]; B = magic(4); % 4x4 magic square whos % Variable info disp("Max of A: " + max(A(:))); % Linear algebra: eigen decomposition [V, D] = eig(A); disp(diag(D)');

📊 Matrix & Array Primitives

🎯 N-dimensional arrays & Special Matrices

zeros, ones, eye, rand, randn, linspace, logspace, reshape, cat, repmat. Multidimensional arrays (ND arrays).

Memory & Array Manipulation

MATLAB preallocates arrays for performance. Functions like zeros(1000) allocate contiguous memory. Reshape and permute alter array shape without copying data (lazy in some contexts). The colon operator 1:10 creates row vectors efficiently. Indexing can be linear indexing (column-major order) or subscript indexing.

📊 Preallocation🔄 Linear Indexing✨ repmat vs bsxfun
% Creating arrays Z = zeros(3, 4); I = eye(5); R = rand(2, 3); vec = 0:0.1:1; % row vector with step lin = linspace(0, 10, 5); % Reshape & concatenation M = [1 2; 3 4]; N = repmat(M, 2, 3); sub = M(1:2, 2); disp(size(sub));

⚡ Vectorized Operations & Indexing

🎯 Element-wise vs Matrix Operators

.* ./ .^ for element-wise; * / ^ for linear algebra. Logical indexing, find, any/all. Broadcasting (implicit expansion since R2016b).

Speed through Vectorization

Vectorized operations avoid slow loops and call compiled C/Fortran routines. Logical indexing selects elements based on conditions: A(A>0.5). Implicit expansion automatically expands singleton dimensions, replacing bsxfun for most operations.

🚀 Element-wise mastery🎯 Logical Indexing📈 Implicit expansion
% Vectorization vs loops A = rand(1000); B = rand(1000); C = A .* B; % element-wise multiplication D = A * B; % matrix multiplication % Logical indexing values = [1,5,2,8,3]; selected = values(values > 3); % Implicit expansion row = 1:5; col = (1:3)'; result = row + col; % 3x5 matrix

📜 Scripts, Functions & Scopes

🎯 M-files, local functions, anonymous functions

Scripts share base workspace; functions have private workspaces. nargin/nargout, varargin/varargout.

Functional Abstraction

MATLAB functions can have multiple outputs. Anonymous functions @(x) x.^2 are lightweight. Subfunctions and nested functions enable encapsulation. Persist variables via persistent keyword.

📂 Function Workspace🔁 Anonymous Functions📦 varargin Patterns
% Example: multiple outputs & anonymous function [avg, stddev] = mystats(x) avg = mean(x); stddev = std(x); end % anonymous & varargin square = @(x) x.^2; result = square(5); disp(result);

📈 2D/3D Plotting & Visualization

🎯 MATLAB Graphics Engine

plot, scatter, bar, histogram, subplot, figure properties. 3D: surf, mesh, contour, scatter3.

Customizing Visualizations

MATLAB's handle graphics allow fine control over every object. gca (current axes), gcf (figure). Use hold on for overlaying plots. Colormaps control surface coloring. Interactive tools like data brushing.

📊 Handle Graphics🌊 3D Visualization🎨 Colormaps
% 2D plot with customization x = linspace(0, 2*pi, 100); y1 = sin(x); y2 = cos(x); plot(x, y1, 'r-', 'LineWidth', 2); hold on; plot(x, y2, 'b--'); grid on; legend('sin', 'cos'); title('Trig Functions'); % 3D surface [X,Y] = meshgrid(-2:0.2:2); Z = X.*exp(-X.^2 - Y.^2); surf(X,Y,Z); colormap(jet);

🗃️ Structs, Cell Arrays & Tables

🎯 Heterogeneous Containers

struct (field-based), cell arrays (hold any types), table (column-oriented data, like DataFrame).

Managing Mixed Data

Cell arrays with curly braces {} can store matrices, strings, etc. Tables are modern, optimized for statistical analysis: readtable imports CSV/Excel. Use struct for key-value hierarchies.

📁 Dynamic fields📊 table for DataFrames{} vs () indexing
% Cell array C = {[1 2], 'text', magic(3)}; disp(C{2}); % Struct student.name = 'Alex'; student.grade = 95; % Table T = table([1;2], {'A';'B'}, 'VariableNames', {'ID', 'Label'}); disp(T);

📉 Data Analysis (Stats & Curve Fitting)

🎯 Statistical & Regression Toolbox

mean, median, std, corrcoef, polyfit, polyval, fitlm, anova. Moving average, filter functions.

Curve Fitting & Regression

Polynomial fitting with polyfit returns coefficients. fitlm builds linear models. cftool interactive GUI. Use filter for smoothing.

📈 polyfit/polyval📉 Pearson Correlation📊 ANOVA test
% Linear regression example x = (0:0.2:5)'; y = 2*x + 1 + 0.5*randn(size(x)); p = polyfit(x, y, 1); y_fit = polyval(p, x); rmse = sqrt(mean((y - y_fit).^2)); disp(['Slope: ', num2str(p(1))]);

🔤 String Manipulation & Regex

🎯 char vs string arrays

Traditional char vectors vs string arrays (R2016b+). regexp, regexprep, split, join, replace.

Powerful Text Processing

String arrays support vectorized operations: lower(str), contains(str, pattern). Regular expressions capture tokens, lookahead/lookbehind.

📝 string arrays🔍 regexp tokens✂️ split/join
% Regex email parsing txt = "Contact: john.doe@example.com, jane@company.org"; emails = regexp(txt, '\w+@\w+\.\w+', 'match'); disp(emails); % String array ops names = ["Alice", "Bob", "Charlie"]; greeting = "Hello, " + names;

💾 High-Performance I/O & MAT-files

🎯 load/save, low-level I/O

MAT-file binary format, textscan, csvread, writetable, fread/fwrite.

Efficient Data Persistence

Saving as -v7.3 uses HDF5 format. matfile objects allow partial loading of huge variables. Textscan for large formatted text files.

💿 MAT-file optimization📂 textscan speed⚡ partial loading
% Save and load data = rand(100); save('mydata.mat', 'data', '-v7'); loaded = load('mydata.mat'); % Write structured table T = array2table(rand(5,3)); writetable(T, 'output.csv');

🏛️ OOP in MATLAB (Classes, Handle)

🎯 value vs handle classes

classdef, properties, methods, events. handle objects (reference behavior).

Advanced Class Design

Value classes copy on assignment; handle classes behave like references. Use enumeration for constants. dependent properties compute on the fly.

🧬 handle vs value📌 property attributes⚡ events & listeners
classdef Person < handle properties Name Age end methods function obj = Person(name, age) obj.Name = name; obj.Age = age; end function greet(obj) fprintf('Hello, %s\n', obj.Name); end end end p = Person('Marie', 28); p.greet();

⚠️ Exception Handling & Debugging

🎯 try-catch, MException

try/catch, throw, rethrow, assert. dbstop for debugging.

Robust Programs

MException provides structured errors. Use warning for non-critical issues. Debugger: breakpoints, step, workspace inspection.

🛡️ try-catch🐞 dbstop in file📢 warning suppression
try x = [1,2; 3,4]; inv(x); catch ME warning('Matrix may be singular: %s', ME.message); result = pinv(x); end assert(isa(x, 'double'), 'Input must be double');

⚡ Performance Optimization (Vectorization)

🎯 Preallocation & vectorized code

Avoid dynamic array growth, use arrayfun, cellfun, logical filters. Profiler tool.

Optimizing MATLAB code

JIT accelerates loops but vectorization often outperforms. Use timeit for benchmarking. In-place operations reduce memory.

⏱️ preallocate📊 logical vectorization🔥 JIT friendly loops
% Bad: growing array tic; x = []; for i=1:10000, x(i)=i^2; end; toc % Good: preallocated tic; x = zeros(1,10000); for i=1:10000, x(i)=i^2; end; toc % Best: vectorized x = (1:10000).^2;

🖥️ Parallel Computing & GPU

🎯 parfor, spmd, gpuArray

Parallel Computing Toolbox: parfor loops, data queues, GPU acceleration.

Scaling up computations

Use parfor for embarrassingly parallel loops. Transfer arrays to GPU with gpuArray for thousands of cores. distributed for clusters.

⚡ parfor🎛️ GPU computing📡 spmd
% GPU acceleration (if supported) A = rand(1000, 'gpuArray'); B = rand(1000, 'gpuArray'); C = A * B; % executed on GPU % Parallel for parfor i = 1:100 result(i) = sin(i) + cos(i); end