{ "cells": [ { "cell_type": "markdown", "id": "cf-0", "metadata": {}, "source": "# Control flow and functions\n\nBranches, loops, anonymous functions, and named functions kept in `.m`\nfiles alongside the notebook." }, { "cell_type": "markdown", "id": "cf-1", "metadata": {}, "source": "## if / elseif / else" }, { "cell_type": "code", "id": "cf-2", "metadata": {}, "execution_count": null, "outputs": [], "source": "x = 7;\nif mod(x, 2) == 0\n disp('even')\nelseif x > 5\n disp('odd and > 5')\nelse\n disp('odd and <= 5')\nend" }, { "cell_type": "markdown", "id": "cf-3", "metadata": {}, "source": "## for and while loops" }, { "cell_type": "code", "id": "cf-4", "metadata": {}, "execution_count": null, "outputs": [], "source": "total = 0;\nfor k = 1:10\n total = total + k;\nend\ntotal" }, { "cell_type": "code", "id": "cf-5", "metadata": {}, "execution_count": null, "outputs": [], "source": "n = 0; p = 1;\nwhile p < 1000\n n = n + 1;\n p = p * 2;\nend\nfprintf('2^%d = %d is the first power of two >= 1000\\n', n, p);" }, { "cell_type": "markdown", "id": "cf-6", "metadata": {}, "source": "## switch" }, { "cell_type": "code", "id": "cf-7", "metadata": {}, "execution_count": null, "outputs": [], "source": "grade = 'B';\nswitch grade\n case 'A'\n disp('excellent')\n case {'B', 'C'}\n disp('good')\n otherwise\n disp('try again')\nend" }, { "cell_type": "markdown", "id": "cf-8", "metadata": {}, "source": "## Anonymous functions, arrayfun, and cellfun" }, { "cell_type": "code", "id": "cf-9", "metadata": {}, "execution_count": null, "outputs": [], "source": "sq = @(x) x.^2;\nsq(1:5)\narrayfun(@(k) k^2, 1:5)\ncellfun(@numel, {'a', 'bb', 'ccc'})" }, { "cell_type": "markdown", "id": "cf-10", "metadata": {}, "source": "## Named functions in `.m` files\n\nCells work like the MATLAB console, so named functions live in `.m` files\nnext to the notebook. This one ships with [fib.m](./fib.m) and\n[minmax.m](./minmax.m); the kernel syncs them into the session so you can\ncall them from cells (and edit them in the file browser)." }, { "cell_type": "code", "id": "cf-11", "metadata": {}, "execution_count": null, "outputs": [], "source": "fibs = arrayfun(@fib, 1:10)\n[lo, hi] = minmax([3 -1 7 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 }