{ "cells": [ { "cell_type": "markdown", "id": "nm-0", "metadata": {}, "source": "# Numerical methods\n\nPolynomials, interpolation, the FFT, statistics, and quadrature." }, { "cell_type": "markdown", "id": "nm-1", "metadata": {}, "source": "## Polynomials: fit, evaluate, roots" }, { "cell_type": "code", "id": "nm-2", "metadata": {}, "execution_count": null, "outputs": [], "source": "x = 0:0.5:5;\ny = 2 * x.^2 - 3 * x + 1;\np = polyfit(x, y, 2)\npolyval(p, 10)\nroots([1 -3 2])'" }, { "cell_type": "markdown", "id": "nm-3", "metadata": {}, "source": "## Interpolation" }, { "cell_type": "code", "id": "nm-4", "metadata": {}, "execution_count": null, "outputs": [], "source": "xs = 0:10;\nys = xs.^2;\ninterp1(xs, ys, 3.5)\ninterp1(xs, ys, [1.5 5.5 8.5])" }, { "cell_type": "markdown", "id": "nm-5", "metadata": {}, "source": "## The FFT" }, { "cell_type": "code", "id": "nm-6", "metadata": {}, "execution_count": null, "outputs": [], "source": "t = 0:0.01:1 - 0.01;\nsig = sin(2 * pi * 5 * t) + 0.5 * sin(2 * pi * 12 * t);\nF = abs(fft(sig));\n[~, idx] = max(F(1:50));\nfprintf('dominant frequency near %d Hz\\n', idx - 1);" }, { "cell_type": "markdown", "id": "nm-7", "metadata": {}, "source": "## Basic statistics" }, { "cell_type": "code", "id": "nm-8", "metadata": {}, "execution_count": null, "outputs": [], "source": "data = [4 8 15 16 23 42];\n[mean(data), median(data), std(data)]\n[min(data), max(data)]" }, { "cell_type": "markdown", "id": "nm-9", "metadata": {}, "source": "## Sorting, differences, cumulative sums" }, { "cell_type": "code", "id": "nm-10", "metadata": {}, "execution_count": null, "outputs": [], "source": "v = [3 1 4 1 5 9 2 6];\nsort(v)\nunique(v)\ncumsum(v)\ndiff(v)" }, { "cell_type": "markdown", "id": "nm-11", "metadata": {}, "source": "## Numerical integration with trapz" }, { "cell_type": "code", "id": "nm-12", "metadata": {}, "execution_count": null, "outputs": [], "source": "x = linspace(0, pi, 200);\napprox = trapz(x, sin(x)) % exact value is 2" } ], "metadata": { "kernelspec": { "display_name": "numbl (MATLAB syntax)", "language": "numbl", "name": "numbl" }, "language_info": { "codemirror_mode": "octave", "file_extension": ".m", "mimetype": "text/x-octave", "name": "numbl", "nbconvert_exporter": "script", "pygments_lexer": "matlab" } }, "nbformat": 4, "nbformat_minor": 5 }