Skill Tracer
Skills › Scientific Agent Skills › matlab › mathematics.md

mathematics.md

212 lines · skills/matlab/references/mathematics.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Numerical Methods, Tolerances, and Reproducibility
2
3This reference targets MATLAB R2026a. Confirm every non-base product before
4using toolbox-specific functions.
5

Numerical Methods, Tolerances, and Reproducibility

This reference targets MATLAB R2026a. Confirm every non-base product before using toolbox-specific functions.

Raw lines 1 to 5
6## Linear systems and decompositions
7
8Solve systems; do not form an inverse as an intermediate:
9
10```matlab
11x = A \ b;
12residual = A*x - b;
13relativeResidual = norm(residual) / ...
14 max(norm(A)*norm(x) + norm(b), realmin(class(A)));
15```
17Check dimensions, rank/conditioning, scaling, symmetry, definiteness, and
18sparsity. A small residual does not guarantee a small forward error for an
19ill-conditioned problem.
21Common base MATLAB operations include:
23- `lu`, `qr`, `chol`, `ldl`, `schur`;
24- `eig`, `svd`, `eigs`, `svds`;
25- `rank`, `cond`, `rcond`, `norm`, `pinv`;
26- `lsqminnorm`, `lsqnonneg`, and backslash least squares.
28Use an economy decomposition where appropriate and request only the spectrum
29needed for large/sparse problems. Eigenvector signs/phases and bases in
30degenerate subspaces are not unique; compare invariant quantities rather than
31raw vectors.

Linear systems and decompositions

Solve systems; do not form an inverse as an intermediate:

x = A \ b;
residual = A*x - b;
relativeResidual = norm(residual) / ...
    max(norm(A)*norm(x) + norm(b), realmin(class(A)));

Check dimensions, rank/conditioning, scaling, symmetry, definiteness, and sparsity. A small residual does not guarantee a small forward error for an ill-conditioned problem.

Common base MATLAB operations include:

  • lu, qr, chol, ldl, schur;
  • eig, svd, eigs, svds;
  • rank, cond, rcond, norm, pinv;
  • lsqminnorm, lsqnonneg, and backslash least squares.

Use an economy decomposition where appropriate and request only the spectrum needed for large/sparse problems. Eigenvector signs/phases and bases in degenerate subspaces are not unique; compare invariant quantities rather than raw vectors.

Raw lines 6 to 32
33## Floating-point comparison
35Binary floating point does not represent most decimal fractions exactly.
36Choose tolerances from the model, scale, conditioning, discretization,
37measurement uncertainty, and algorithm—not from a universal constant.
39A robust scalar/elementwise policy often has the form:
41```matlab
42errorMagnitude = abs(actual - expected);
43limit = absoluteTolerance + relativeTolerance .* abs(expected);
44isAcceptable = errorMagnitude <= limit;
45```
47Handle these explicitly:
49- expected values near zero need an absolute tolerance;
50- large expected values often need a relative tolerance;
51- `NaN` equality is a semantic decision (`isequaln` differs from `==`);
52- `Inf` signs should match when infinity is expected;
53- class, size, sparsity, and complex values are part of the contract.
55R2026a documents `isapprox` alongside equality operations. In
56`matlab.unittest`, use `AbsTol`/`RelTol` or
57`AbsoluteTolerance`/`RelativeTolerance`. Record why values are scientifically
58acceptable.
60Do not widen tolerances automatically after an upgrade. First investigate RNG,
61ordering, reduction order, solver defaults/options, data type, threading,
62compiler, library, and release-note changes.

Floating-point comparison

Binary floating point does not represent most decimal fractions exactly. Choose tolerances from the model, scale, conditioning, discretization, measurement uncertainty, and algorithm—not from a universal constant.

A robust scalar/elementwise policy often has the form:

errorMagnitude = abs(actual - expected);
limit = absoluteTolerance + relativeTolerance .* abs(expected);
isAcceptable = errorMagnitude <= limit;

Handle these explicitly:

  • expected values near zero need an absolute tolerance;
  • large expected values often need a relative tolerance;
  • NaN equality is a semantic decision (isequaln differs from ==);
  • Inf signs should match when infinity is expected;
  • class, size, sparsity, and complex values are part of the contract.

R2026a documents isapprox alongside equality operations. In matlab.unittest, use AbsTol/RelTol or AbsoluteTolerance/RelativeTolerance. Record why values are scientifically acceptable.

Do not widen tolerances automatically after an upgrade. First investigate RNG, ordering, reduction order, solver defaults/options, data type, threading, compiler, library, and release-note changes.

Raw lines 33 to 63
64## Random streams
66Record algorithm and seed, not only a seed:
68```matlab
69rng(1729, "twister");
70stateAtStart = rng;
71samples = randn(1000, 1);
72```
74For local independent streams:
76```matlab
77stream = RandStream("Threefry", Seed=1729);
78stream.Substream = 4;
79samples = randn(stream, 1000, 1);
80```
82Generator availability and bitwise sequences can vary by algorithm/release.
83Avoid `rng("shuffle")` for reproducible work. On parallel workers, time-based
84seeding can collide; use supported independent streams/substreams and record
85worker mapping. Parallel computing requires Parallel Computing Toolbox.

Random streams

Record algorithm and seed, not only a seed:

rng(1729, "twister");
stateAtStart = rng;
samples = randn(1000, 1);

For local independent streams:

stream = RandStream("Threefry", Seed=1729);
stream.Substream = 4;
samples = randn(stream, 1000, 1);

Generator availability and bitwise sequences can vary by algorithm/release. Avoid rng("shuffle") for reproducible work. On parallel workers, time-based seeding can collide; use supported independent streams/substreams and record worker mapping. Parallel computing requires Parallel Computing Toolbox.

Raw lines 64 to 86
87## Integration, roots, and differential equations
89Base MATLAB provides general numerical methods including:
91- `integral`, `integral2`, `integral3`, `trapz`, `cumtrapz`;
92- `gradient`, `diff`;
93- `fzero`;
94- ODE solvers such as `ode45`, `ode23`, `ode113`, `ode15s`, `ode23s`,
95 `ode23t`, and `ode23tb`;
96- boundary-value solvers such as `bvp4c` and `bvp5c`.
98Define tolerances and failure criteria:
100```matlab
101options = odeset( ...
102 RelTol=1e-7, ...
103 AbsTol=1e-10, ...
104 MaxStep=0.05);
105[t, y] = ode45(@rhs, [0 5], 1, options);
106```
108Solver tolerances control local error estimates, not proof of a globally
109correct model. Check conservation laws, event localization, stiffness,
110step-size convergence, and an independent formulation. R2026a adds an
111automatic-differentiation Jacobian option for the `ode` object; verify the
112specific solver/problem and release notes before using it.
113R2026b extends `ode` automatic Jacobians to complex equations and adds the
114`Waypoints` property for time values the solver must reach exactly. These are
115release-specific `ode` object features, not `ode45` options.

Integration, roots, and differential equations

Base MATLAB provides general numerical methods including:

  • integral, integral2, integral3, trapz, cumtrapz;
  • gradient, diff;
  • fzero;
  • ODE solvers such as ode45, ode23, ode113, ode15s, ode23s, ode23t, and ode23tb;
  • boundary-value solvers such as bvp4c and bvp5c.

Define tolerances and failure criteria:

options = odeset( ...
    RelTol=1e-7, ...
    AbsTol=1e-10, ...
    MaxStep=0.05);
[t, y] = ode45(@rhs, [0 5], 1, options);

Solver tolerances control local error estimates, not proof of a globally correct model. Check conservation laws, event localization, stiffness, step-size convergence, and an independent formulation. R2026a adds an automatic-differentiation Jacobian option for the ode object; verify the specific solver/problem and release notes before using it. R2026b extends ode automatic Jacobians to complex equations and adds the Waypoints property for time values the solver must reach exactly. These are release-specific ode object features, not ode45 options.

Raw lines 87 to 116
117## Optimization and fitting boundaries
119Base MATLAB includes `fminsearch` and `fminbnd`. These do not replace
120constrained or specialized solvers.
122Examples of separately licensed boundaries:
124| Capability | Representative API | Product to confirm |
125|---|---|---|
126| constrained/nonlinear optimization | `fmincon`, `fminunc`, `lsqnonlin`, `lsqcurvefit` | Optimization Toolbox |
127| global/metaheuristic optimization | `ga`, `particleswarm`, `surrogateopt` | Global Optimization Toolbox |
128| curve fitting objects/apps | `fit`, Curve Fitter | Curve Fitting Toolbox |
129| statistical modeling/distributions | `fitlm`, `fitdist`, `anova`, many tests | Statistics and Machine Learning Toolbox |
130| symbolic algebra | `syms`, `solve`, symbolic differentiation | Symbolic Math Toolbox |
131| signal design/analysis | `fir1`, `filtfilt`, `designfilt`, `spectrogram` | Signal Processing Toolbox |
132| parallel loops/GPU | `parfor`, `parpool`, `gpuArray` | Parallel Computing Toolbox |
134Some base functions have similarly named toolbox alternatives. Check the
135function's current product page and the project dependency report; never infer
136ownership from a code example.
138Optimization reproducibility requires objective/constraint definitions,
139starting points, bounds, solver/options, stopping tolerances, gradients,
140scaling, RNG state for stochastic methods, and exit diagnostics. Compare
141feasibility and optimality measures, not only the objective value.

Optimization and fitting boundaries

Base MATLAB includes fminsearch and fminbnd. These do not replace constrained or specialized solvers.

Examples of separately licensed boundaries:

CapabilityRepresentative APIProduct to confirm
constrained/nonlinear optimizationfmincon, fminunc, lsqnonlin, lsqcurvefitOptimization Toolbox
global/metaheuristic optimizationga, particleswarm, surrogateoptGlobal Optimization Toolbox
curve fitting objects/appsfit, Curve FitterCurve Fitting Toolbox
statistical modeling/distributionsfitlm, fitdist, anova, many testsStatistics and Machine Learning Toolbox
symbolic algebrasyms, solve, symbolic differentiationSymbolic Math Toolbox
signal design/analysisfir1, filtfilt, designfilt, spectrogramSignal Processing Toolbox
parallel loops/GPUparfor, parpool, gpuArrayParallel Computing Toolbox

Some base functions have similarly named toolbox alternatives. Check the function's current product page and the project dependency report; never infer ownership from a code example.

Optimization reproducibility requires objective/constraint definitions, starting points, bounds, solver/options, stopping tolerances, gradients, scaling, RNG state for stochastic methods, and exit diagnostics. Compare feasibility and optimality measures, not only the objective value.

Raw lines 117 to 142
143## Statistics and signal processing
145Base array summaries include `mean`, `median`, `std`, `var`, `min`, `max`,
146`movmean`, `movmedian`, `cov`, `corrcoef`, `histcounts`, and polynomial
147`polyfit`/`polyval`. Some distribution, model, hypothesis-test, robust,
148classification, and specialized plotting APIs require Statistics and Machine
149Learning Toolbox.
151For FFT work:
153```matlab
154n = numel(x);
155Y = fft(x);
156frequency = (0:n-1).' * (sampleRate/n);
157```
159Document sample rate, units, window, detrending, normalization, one- versus
160two-sided spectrum, zero padding, and endpoint convention. `fft` and `conv` are
161base MATLAB; many filter-design and spectral-estimation functions are Signal
162Processing Toolbox.

Statistics and signal processing

Base array summaries include mean, median, std, var, min, max, movmean, movmedian, cov, corrcoef, histcounts, and polynomial polyfit/polyval. Some distribution, model, hypothesis-test, robust, classification, and specialized plotting APIs require Statistics and Machine Learning Toolbox.

For FFT work:

n = numel(x);
Y = fft(x);
frequency = (0:n-1).' * (sampleRate/n);

Document sample rate, units, window, detrending, normalization, one- versus two-sided spectrum, zero padding, and endpoint convention. fft and conv are base MATLAB; many filter-design and spectral-estimation functions are Signal Processing Toolbox.

Raw lines 143 to 163
164## Verification patterns
166Use several layers:
1681. **Dimensional/invariant checks**: sizes, units, conservation, monotonicity,
169 positivity, symmetry.
1702. **Analytic cases**: small problems with known solutions.
1713. **Refinement studies**: mesh, step, quadrature, or tolerance convergence.
1724. **Independent implementation**: alternative solver or formulation.
1735. **Condition/sensitivity analysis**: perturb inputs and options.
1746. **Release comparison**: compare scientifically meaningful observables with
175 a documented tolerance.
1767. **Performance measurement**: after correctness, measure representative
177 workloads with `timeit`.
179Do not claim bitwise reproducibility across releases, hardware, thread counts,
180GPU/CPU, or external libraries unless it was actually tested and documented.

Verification patterns

Use several layers:

  1. Dimensional/invariant checks: sizes, units, conservation, monotonicity, positivity, symmetry.
  2. Analytic cases: small problems with known solutions.
  3. Refinement studies: mesh, step, quadrature, or tolerance convergence.
  4. Independent implementation: alternative solver or formulation.
  5. Condition/sensitivity analysis: perturb inputs and options.
  6. Release comparison: compare scientifically meaningful observables with a documented tolerance.
  7. Performance measurement: after correctness, measure representative workloads with timeit.

Do not claim bitwise reproducibility across releases, hardware, thread counts, GPU/CPU, or external libraries unless it was actually tested and documented.

Raw lines 164 to 181
182## Reproducibility record
184At minimum capture:
186- MATLAB release/update or Octave version;
187- OS and architecture, only as named fields;
188- required products and license status separately;
189- source/input hashes and schema versions;
190- numeric classes and shapes;
191- RNG algorithm, seed, substream, and parallel mapping;
192- solver names/options/tolerances and stopping diagnostics;
193- expected invariants and acceptance tolerances;
194- output format/version and graphics export settings.
196Use `scripts/reproducibility_report.py` to hash only named local artifacts. It
197does not inspect the broad environment.

Reproducibility record

At minimum capture:

  • MATLAB release/update or Octave version;
  • OS and architecture, only as named fields;
  • required products and license status separately;
  • source/input hashes and schema versions;
  • numeric classes and shapes;
  • RNG algorithm, seed, substream, and parallel mapping;
  • solver names/options/tolerances and stopping diagnostics;
  • expected invariants and acceptance tolerances;
  • output format/version and graphics export settings.

Use scripts/reproducibility_report.py to hash only named local artifacts. It does not inspect the broad environment.

Raw lines 182 to 198
Runs code scripts/reproducibility_report.py :196
199## Sources (reviewed 2026-10-01)
201- [Linear Algebra](https://www.mathworks.com/help/matlab/linear-algebra.html)
202- [`mldivide`](https://www.mathworks.com/help/matlab/ref/double.mldivide.html)
203- [`eq` floating-point guidance and `isapprox`](https://www.mathworks.com/help/matlab/ref/double.eq.html)
204- [`AbsoluteTolerance`](https://www.mathworks.com/help/matlab/ref/matlab.unittest.constraints.absolutetolerance-class.html)
205- [`RelativeTolerance`](https://www.mathworks.com/help/matlab/ref/matlab.unittest.constraints.relativetolerance-class.html)
206- [`rng`](https://www.mathworks.com/help/matlab/ref/rng.html)
207- [`RandStream`](https://www.mathworks.com/help/matlab/ref/randstream.html)
208- [ODE Solvers](https://www.mathworks.com/help/matlab/ordinary-differential-equations.html)
209- [`ode` properties and version history](https://www.mathworks.com/help/matlab/ref/ode.html)
210- [Optimization](https://www.mathworks.com/help/matlab/optimization.html)
211- [MATLAB product list and pricing/licensing](https://www.mathworks.com/pricing-licensing.html)
212- [MATLAB release notes](https://www.mathworks.com/help/matlab/release-notes.html)

Sources (reviewed 2026-10-01)

  • Linear Algebra
  • [mldivide](https://www.mathworks.com/help/matlab/ref/double.mldivide.html)
  • [eq floating-point guidance and isapprox](https://www.mathworks.com/help/matlab/ref/double.eq.html)
  • [AbsoluteTolerance](https://www.mathworks.com/help/matlab/ref/matlab.unittest.constraints.absolutetolerance-class.html)
  • [RelativeTolerance](https://www.mathworks.com/help/matlab/ref/matlab.unittest.constraints.relativetolerance-class.html)
  • [rng](https://www.mathworks.com/help/matlab/ref/rng.html)
  • [RandStream](https://www.mathworks.com/help/matlab/ref/randstream.html)
  • ODE Solvers
  • [ode properties and version history](https://www.mathworks.com/help/matlab/ref/ode.html)
  • Optimization
  • MATLAB product list and pricing/licensing
  • MATLAB release notes
Raw lines 199 to 212