UcenlyOpen in the app

Mathematical Applications · BE5B15MAA · Topic 4 of 13

Functions in Matlab 1: control flow, debugging, user defined functions

Week 4. Loops and branches decide what runs, and a function file turns a recipe into a reusable command. Debugging material is still pending.

Open the interactive lesson

Key ideas

Loops, conditions and switch

for index=start:step:end repeats a fixed number of times, while expression repeats as long as the test holds, and both close with end. if / elseif / else chooses one branch. switch expression compares the value with each case and runs otherwise when none fits.

A user defined function

The first line of the file is the header function [out1,out2,...] = name(in1,in2,...). Variables inside are local. nargin and nargout tell how many inputs and outputs a call used, so a missing input can get a default value. A further function in the same file is treated as a subfunction.

Exam style: a sequence up to a limit

A sample exam task asks for a function that returns the Fibonacci numbers while every new element stays below a given limit, and for a script that calls it with 1000 and plots the sequence against n. A while loop that appends the next number only while it stays below the limit does it.

In one line: A loop needs its stop rule, a function needs its header, and nargin is how a function learns what the caller gave it.

Formulas

Sources

Written by Ucenly. Based on the BE5B15MAA course materials: