Lesson 03-MATLAB Program Structure and Flow Control

Introduction: MATLAB as a Programming Language

When most people first encounter MATLAB, they see it as a glorified calculator—a tool for performing mathematical computations and visualizing data. And indeed, MATLAB excels at interactive computing. But to relegate MATLAB to the status of a “calculator” is to fundamentally misunderstand its nature. MATLAB is a full-fledged programming language, with all the features you’d expect from a modern language: flow control, functions, data structures, input/output, object-oriented programming, and even parallelism.

In this comprehensive guide, we’re going to dive deep into MATLAB’s programming capabilities. We’ll explore the difference between scripts and functions (and when to use each), master flow control constructs (if/else, switch, for, while), and learn one of the most important skills in MATLAB programming: vectorization.

But we’re not going to stop at the “how.” We’re going to explore the “why.” Why is vectorized code so much faster than loop-based code? How does MATLAB’s JIT (Just-In-Time) compiler work, and why does it make some loops fast but not others? What are the deep architectural reasons behind MATLAB’s performance characteristics?

By the time you finish this article, you’ll be able to write MATLAB code that’s not just correct, but elegant, efficient, and maintainable. You’ll understand the performance implications of your coding choices, and you’ll be able to leverage MATLAB’s unique strengths to solve complex engineering and scientific problems.

MATLAB as a Programming Language: Interpreter vs. JIT Acceleration

To understand how to write effective MATLAB code, you need to understand how MATLAB executes the code you write. This requires a dive into the internal architecture of the MATLAB execution engine—a journey that will illuminate many of MATLAB’s performance characteristics.

The Evolution from Pure Interpretation to JIT Compilation

In the earliest versions of MATLAB (the 1980s), the language was purely interpreted. When you typed a command, MATLAB would parse it, execute it immediately, and then move on to the next command. There was no compilation step, no optimization, and no translation to machine code. This made MATLAB highly interactive and easy to learn, but it also made it slow—especially for loops.

Consider this simple loop in old MATLAB:

for i = 1:1000000
    x(i) = i^2;
end

In a purely interpreted environment, this loop would be excruciatingly slow. Each iteration would require MATLAB to:

  1. Parse the expression i^2
  2. Look up the variable i
  3. Compute the square
  4. Look up or create the variable x
  5. Assign the result to x(i)
  6. Increment i
  7. Check the loop condition

Each of these steps involves function calls, memory allocations, and overhead that adds up dramatically over a million iterations.

Enter the JIT Compiler

Starting with MATLAB 6.5 (Release 13) in 2002, MathWorks introduced a JIT (Just-In-Time) compiler for the MATLAB language. The JIT compiler changed everything.

Here’s how it works:

  1. Parsing: When you run a script or function, MATLAB first parses your code into an intermediate representation (IR).
  2. JIT Compilation: The JIT compiler examines the IR and identifies sections of code that can be compiled to machine code. This typically includes:
    • for loops with simple bodies
    • Arithmetic operations
    • Array indexing operations
    • Built-in functions
  3. Execution: The compiled machine code is executed. For sections that couldn’t be compiled, MATLAB falls back to interpreted execution.

The result? Loops in MATLAB can now approach the speed of compiled languages like C—if the JIT compiler can handle them.

What the JIT Compiler Can and Cannot Do

The JIT compiler is powerful, but it has limitations. It works best with code that is:

  • Simple and predictable: Straightforward arithmetic, array operations, and loops.
  • Type-stable: Variables that don’t change type inside a loop.
  • Size-stable: Arrays that don’t change size inside a loop (this is called “pre-allocation,” and we’ll discuss it extensively later).

The JIT compiler struggles with code that is:

  • Too dynamic: Code that uses eval(), feval(), or other dynamic features.
  • Object-oriented: Code that calls methods on MATLAB objects (the JIT can’t always determine which method will be called).
  • Too complex: Code with deeply nested function calls, or code that uses cell arrays or structure arrays in complex ways.

Let me illustrate with an example:

% Example 1: JIT can compile this (simple loop, type-stable, size-stable)
x = zeros(1, 1000000);      % PRE-ALLOCATE!
for i = 1:1000000
    x(i) = i^2;
end

% Example 2: JIT cannot compile this (growing array inside loop)
x = [];                        % NOT pre-allocated!
for i = 1:1000000
    x(i) = i^2;              % x grows on every iteration—very slow!
end

% Example 3: JIT might be able to compile this (if the function is known)
for i = 1:1000000
    x(i) = my_function(i);    % Depends on my_function—can JIT inline it?
end

In Example 1, the JIT compiler can analyze the loop, see that x is pre-allocated and doesn’t change size, and compile the loop to efficient machine code.

In Example 2, x is not pre-allocated. On each iteration, MATLAB has to grow the array x by one element. This involves allocating a new, larger array and copying all the old elements to the new array—an O(n²) operation that the JIT compiler cannot optimize away.

In Example 3, whether the JIT compiler can optimize the loop depends on my_function. If my_function is a simple built-in function, the JIT compiler might be able to inline it. If it’s a complex user-defined function, the JIT compiler might not be able to analyze it, and the loop will run in interpreted mode.

How to Tell if Your Code is Being JIT-Compiled

Unfortunately, MATLAB doesn’t provide a direct way to check if a specific piece of code was JIT-compiled. However, you can infer it from performance:

% Time a loop
tic;
x = zeros(1, 1000000);
for i = 1:1000000
    x(i) = i^2;
end
t = toc;
fprintf('Time: %.4f seconds\n', t);

If the loop runs surprisingly fast (comparable to C), it’s likely being JIT-compiled. If it’s slow, it’s likely running in interpreted mode.

You can also use the Profiler to identify which lines of code are taking the most time. If a simple loop is taking a disproportionate amount of time, it’s a sign that the JIT compiler isn’t optimizing it.

>> profile on
>> my_slow_function
>> profile viewer

The Future: MATLAB’s New Execution Engine (MXE)

In recent versions of MATLAB (R2015b and later), MathWorks introduced a new execution engine called the MATLAB Execution Engine (MXE). This new engine provides:

  • Faster execution of MATLAB code
  • Better support for object-oriented programming
  • Improved handling of large data sets
  • More consistent performance across different platforms

The MXE represents a significant architectural shift in how MATLAB executes code, moving away from the legacy interpreter towards a more modern, compilation-based approach. While the details are proprietary, the trend is clear: MathWorks is investing heavily in making MATLAB code execute faster, narrowing the gap with compiled languages.

Membership Required

You must be a member to access this content.

View Membership Levels

Already a member? Log in here
Share your love