05 Programming Flow, Scripts & Functions

Overview: Flow Control and Scope Boundaries

MATLAB separates execution structures into scripts and scope-isolated functions. This note details workspace scope dynamics, function variations, control loops, and diagnostic timing.


1. Scripts vs. Functions (Workspace Scopes)

  • Script: A series of instructions executed in the caller’s global workspace. If a script modifies a variable x, it alters x in the active command shell.
  • Function: Runs in its own isolated local workspace. Variables declared inside a function are deleted when it terminates, preventing side effects in the global workspace.

2. Function Variations

Primary Functions:

The main function declared at the top of a .m file. Its name must match the file name (e.g. myFunc.m must begin with function output = myFunc(input)).

Subfunctions (Local Functions):

Helper functions defined at the bottom of the same file. They are only visible to other functions in that file.

Nested Functions:

Functions defined inside the body of a parent function.

  • Mechanics: They share scope, meaning they can directly read and modify variables in the parent function’s workspace without passing them as arguments.

Anonymous Functions:

Single-line functions defined inline without creating a new file.

  • Syntax: f_handle = @(arg1, arg2, ...) expression
  • Description: Defines an inline function mapping inputs to an output expression, returning a function handle.
  • Example: sqr = @(x) x.^2; called as sqr(5).

3. Control Flow Structures

Conditonal Structures:

if (a > 10)
    disp('Greater than 10')
elseif (a == 10)
    disp('Equal to 10')
else
    disp('Less than 10')
end

Loops:

  • for Loop Syntax: for index = start:step:end
  • while Loop Syntax: while (condition)

Loop Performance Bottleneck

Iterative loops (for/while) are relatively slow in MATLAB’s interpreter. Always prefer Vectorized Operations (e.g., y = x.^2 instead of looping through each element) to take advantage of optimized BLAS/LAPACK matrix math libraries under the hood.


4. Diagnostics and Timing

  • tic / toc
    • Syntax: tic (starts stopwatch), t = toc (returns elapsed time).
    • Description: Measures code execution speed.
  • keyboard
    • Syntax: keyboard
    • Description: Pauses program execution and hands control back to the command prompt. This allows you to inspect and modify local variables in the function’s workspace. Type return to resume or dbquit to terminate the program.

💻 Conceptual Code Demonstration

function main_demo()
    % Primary Function Scope
    fprintf('Starting main demo...\n');
    
    % 1. Use anonymous function
    % Syntax: handle = @(x) expression
    quadFunc = @(x) x.^2 + 2*x + 1;
    fprintf('Anonymous eval f(3): %d\n', quadFunc(3));
    
    % 2. Code execution timing
    tic;
    loop_demo(1000);
    elapsed = toc;
    fprintf('Loop elapsed time: %f seconds\n', elapsed);
end
 
function loop_demo(maxLimit)
    % Subfunction Scope (only visible to main_demo)
    sumVal = 0;
    for k = 1:maxLimit
        sumVal = sumVal + k;
    end
    
    % keyboard % Uncomment to halt execution here and inspect 'sumVal'
end