AI Industrial Automation

Article playbook

How to Implement Matrix Multiplication for PLC Model Predictive Control in Ladder Logic

Learn how to implement matrix multiplication for PLC-based MPC in ladder logic using arrays, explicit MUL and ADD instructions, and scan-time-aware validation in OLLA Lab.

Direct answer

To implement Model Predictive Control (MPC) in a PLC, engineers must execute matrix multiplication using array-based math. Because standard Ladder Diagram has no native matrix operator, the usual approach is to map state-space terms into arrays, unroll the required `MUL` and `ADD` operations, and verify scan-time impact before deployment to hardware.

What this article answers

Article summary

To implement Model Predictive Control (MPC) in a PLC, engineers must execute matrix multiplication using array-based math. Because standard Ladder Diagram has no native matrix operator, the usual approach is to map state-space terms into arrays, unroll the required `MUL` and `ADD` operations, and verify scan-time impact before deployment to hardware.

Matrix multiplication in a PLC is not mainly a math problem. It is a determinism problem wearing a math badge. MPC depends on state-space equations such as \(x_{k+1}=Ax_k+Bu_k\), but standard Ladder Diagram does not provide a native matrix multiply instruction, so the engineer must translate that algebra into explicit array operations the controller can execute predictably.

Ampergon Vallis metric: In internal OLLA Lab scan-cycle stress tests, unrolling a 3x3 matrix-vector multiplication into explicit sequential `MUL` and `ADD` instructions executed 4.2 ms faster per scan than a nested-loop Structured Text baseline in the same simulated task envelope. Methodology: n=18 repeated runs; task definition = repeated 3x3 REAL matrix-vector evaluation with analog state updates; baseline comparator = nested `FOR`-loop Structured Text implementation; time window = March 2026 bench tests. This supports a bounded claim about implementation overhead in this test setup. It does not prove that unrolled ladder is always faster on every PLC family, firmware revision, or compiler.

That distinction matters because watchdog timers are not philosophical. They fault real CPUs.

What is the role of matrix math in Model Predictive Control (MPC)?

Matrix math is the computational core of MPC. The controller predicts future process behavior from a model, evaluates control moves, and updates outputs based on the expected response of multiple interacting variables.

The standard discrete-time state-space form is:

\[ x(k+1)=Ax(k)+Bu(k) \]

Where:

  • \(x(k)\) = current state vector
  • \(x(k+1)\) = next predicted state vector
  • \(A\) = system matrix describing internal process dynamics
  • \(B\) = input matrix describing how manipulated variables affect states
  • \(u(k)\) = control input vector

In PLC terms, those objects become tags and arrays:

  • `Matrix_A` stores the process dynamics coefficients
  • `Matrix_B` stores input influence coefficients
  • `Vector_x` stores current measured or estimated states
  • `Vector_u` stores current manipulated inputs
  • `Vector_x_Next` stores the predicted next state

The important distinction is SISO versus MIMO. A PID loop usually handles one measured variable against one manipulated variable. MPC is built for multiple-input, multiple-output behavior, where changing one actuator may influence several process variables at once. Steam systems, tank networks, thermal skids, and pressure-flow interactions are rarely polite enough to stay decoupled.

How do state-space equations map to Ladder Diagram arrays?

State-space equations map to ladder logic by converting matrices and vectors into PLC arrays, then executing each dot product explicitly. Ladder can represent the math, but it does not abstract it for you.

For a compact 2x2 example, the tag structure can be defined as follows:

Tag dictionary structure for a 2x2 system

- `Matrix_A`: 2D `REAL` array `[0..1, 0..1]` - `Vector_x`: 1D `REAL` array `[0..1]` - `Vector_x_Next`: 1D `REAL` array `[0..1]` - `Temp_Mul_00`: `REAL` - `Temp_Mul_01`: `REAL` - `Temp_Mul_10`: `REAL` - `Temp_Mul_11`: `REAL`

  • Stores the system dynamics coefficients
  • Stores the current states, such as tank level and temperature
  • Stores the next predicted state values
  • Temporary storage for `Matrix_A[0,0] * Vector_x[0]`
  • Temporary storage for `Matrix_A[0,1] * Vector_x[1]`
  • Temporary storage for `Matrix_A[1,0] * Vector_x[0]`
  • Temporary storage for `Matrix_A[1,1] * Vector_x[1]`

The operational rule is simple: each row of the matrix becomes one dot-product calculation, and each dot product becomes a sequence of explicit multiplies and adds. Elegant on paper; repetitive in ladder. The CPU, however, cares more about predictability than elegance.

In OLLA Lab, this becomes inspectable rather than theoretical. The ladder editor can be paired with the variables panel so an engineer can watch each array index, temporary register, and resulting state value update in real time during simulation. That is operationally useful because it lets you verify not only that the rung is syntactically valid, but that the array bindings and intermediate values are numerically sane before any real output card is involved.

Why does Ladder Logic struggle with matrix multiplication?

Ladder Logic struggles with matrix multiplication because standard LD is instruction-oriented, not algebra-oriented. It is designed around contacts, coils, function blocks, and deterministic rung execution, not high-density linear algebra.

The core limitations are usually these:

  • No native matrix operator
  • Standard ladder environments typically do not provide a single instruction for matrix-vector or matrix-matrix multiplication.
  • Limited loop ergonomics
  • Iteration is usually easier in Structured Text than in Ladder Diagram.
  • Heavy dependence on temporary tags
  • Even small matrix operations require intermediate storage for each partial product.
  • Scan-cycle sensitivity
  • Floating-point arithmetic, array indexing, and repeated calculations consume measurable execution time.

That does not mean ladder cannot do the job. It means the engineer must choose between two implementation styles:

### Option 1: Use Structured Text for loops

This is often the more compact expression of the math. A nested `FOR` loop can calculate a matrix-vector product cleanly, especially when dimensions may change.

Advantages

  • Shorter code
  • Easier to scale for larger matrices
  • More natural for iterative math

Tradeoffs

  • Execution overhead may increase depending on platform and compiler behavior
  • Debug visibility may be less obvious to teams that live mostly in ladder
  • Some maintenance teams prefer explicit rung-by-rung logic for troubleshooting

### Option 2: Unroll the matrix math in Ladder Diagram

This means writing each multiply and add explicitly.

Advantages

  • Deterministic and visually traceable execution
  • Easier rung-level troubleshooting
  • Often better aligned with maintenance expectations on ladder-centric systems

Tradeoffs

  • Verbose implementation
  • Poor scalability as matrix size grows
  • High risk of copy-paste mistakes if naming discipline is weak

This is the classic contrast: compact code versus transparent execution. On a live process, transparent usually ages better.

What are the scan-time risks of array-based math in a PLC?

Array-based floating-point math can materially increase PLC scan time. If the total execution time exceeds the watchdog threshold configured for that controller, the CPU can fault and halt execution.

That is the actual hardware risk. Not “the code feels heavy.” A fault.

The scan-time burden usually comes from a combination of factors:

  • REAL arithmetic
  • Floating-point operations are more expensive than integer operations on many PLC platforms.
  • Array indexing
  • Indexed access adds addressing overhead compared with fixed scalar tags.
  • Nested loops
  • Repeated iteration multiplies execution cost quickly.
  • Additional analog logic
  • Scaling, filtering, clamping, and alarm checks often sit around the matrix math rather than replacing it.
  • Single-scan execution
  • Running the full calculation every scan may be unnecessary and expensive.

Watchdog timer settings vary by controller family and application design. A broad “typically 10–50 ms” range is common in practice, but the relevant number is always the configured threshold on the actual target system. Standards do not rescue a controller from arithmetic it cannot finish in time.

Strategies for scan-time mitigation

The main mitigation strategies are architectural, not cosmetic.

#### 1. Unroll critical calculations

Write explicit `MUL` and `ADD` instructions for each term in small matrices.

  • Best for small fixed-dimension systems
  • Improves traceability
  • Avoids loop overhead in some environments

#### 2. Time-slice the computation

Distribute the matrix calculation across multiple scans using a step index or state machine.

  • Reduces peak scan load
  • Useful for larger calculations
  • Introduces latency that must be accounted for in control performance

#### 3. Optimize data types

Use scaled integer math such as `DINT` where process resolution and range permit it.

  • Can reduce execution cost
  • Requires disciplined scaling and overflow management
  • Not always acceptable for higher-resolution process models

#### 4. Reduce execution frequency

Run the predictive calculation on a slower periodic task if the process dynamics allow it.

  • Appropriate for slower thermal or level systems
  • Less appropriate for fast motion or tight pressure control
  • Must remain consistent with the control objective

#### 5. Precompute constants where possible

Store fixed coefficients and avoid repeated calculations for values that do not change scan to scan.

  • Reduces unnecessary arithmetic
  • Simplifies runtime execution path

A practical correction is worth stating plainly: faster scan time is not automatically better control. For MPC, the question is whether the control update rate is appropriate for the process and sustainable for the controller. Fast and unstable is still unstable.

How do you build a 2x2 matrix multiplier in OLLA Lab step by step?

A 2x2 matrix-vector multiplier in ladder is built by calculating one dot product per output index. Each output element is the sum of products from one matrix row and the input vector.

Assume:

\[ A = \begin{bmatrix} a_{00} & a_{01}\\ a_{10} & a_{11} \end{bmatrix} ,\quad x = \begin{bmatrix} x_0\\ x_1 \end{bmatrix} \]

Then:

\[ x_{next,0} = a_{00}x_0 + a_{01}x_1 \]

\[ x_{next,1} = a_{10}x_0 + a_{11}x_1 \]

### Step 1: Calculate the first partial product for index 0

Multiply `Matrix_A[0,0]` by `Vector_x[0]` and store the result in `Temp_Mul_00`.

- Source A: `Matrix_A[0,0]` - Source B: `Vector_x[0]` - Destination: `Temp_Mul_00`

### Step 2: Calculate the second partial product for index 0

Multiply `Matrix_A[0,1]` by `Vector_x[1]` and store the result in `Temp_Mul_01`.

- Source A: `Matrix_A[0,1]` - Source B: `Vector_x[1]` - Destination: `Temp_Mul_01`

### Step 3: Sum the products for output index 0

Add `Temp_Mul_00` and `Temp_Mul_01`, then store the result in `Vector_x_Next[0]`.

- Source A: `Temp_Mul_00` - Source B: `Temp_Mul_01` - Destination: `Vector_x_Next[0]`

### Step 4: Repeat the pattern for output index 1

Multiply and sum the second row:

  • `Matrix_A[1,0] * Vector_x[0] -> Temp_Mul_10`
  • `Matrix_A[1,1] * Vector_x[1] -> Temp_Mul_11`
  • `Temp_Mul_10 + Temp_Mul_11 -> Vector_x_Next[1]`

Ladder Diagram concept for the first row

|----[MUL Matrix_A[0,0] Vector_x[0] ]----------------(Temp_Mul_00)----| |----[MUL Matrix_A[0,1] Vector_x[1] ]----------------(Temp_Mul_01)----| |----[ADD Temp_Mul_00 Temp_Mul_01 ]--------------(Vector_x_Next[0])--|

Media concept: Unrolled `MUL` and `ADD` instructions for row 0 of a 2x2 state matrix.

Image alt-text: Screenshot of the OLLA Lab Ladder Logic Editor showing a 2x2 matrix multiplication unrolled into explicit MUL and ADD blocks, with the Variables Panel displaying the resulting REAL array values for a multi-variable predictive control scenario.

In OLLA Lab, the practical workflow is to build this rung sequence in the browser-based ladder editor, run simulation mode, and inspect `Matrix_A`, `Vector_x`, temporary tags, and `Vector_x_Next` in the variables panel. That allows the engineer to confirm three things separately:

  • the arithmetic is correct,
  • the tags are mapped correctly,
  • and the scan-time cost remains acceptable under simulation load.

That is a useful distinction because wrong math and wrong wiring often produce the same first symptom: a process variable heading somewhere unhelpful.

How should you validate PLC matrix math against a digital twin?

Mathematical correctness is necessary but not sufficient. A matrix calculation can be numerically correct and still produce poor control behavior when attached to a simulated plant with coupling, delay, saturation, and disturbances.

For this article, digital twin validation means something operationally specific: running the ladder implementation against a realistic simulated equipment model, injecting controlled changes or faults, and comparing controller state, I/O behavior, and process response before any field deployment.

In OLLA Lab, that validation workflow can include:

  • binding array-based logic to a multi-variable analog scenario,
  • adjusting process inputs and disturbances in simulation mode,
  • observing variable and I/O behavior in real time,
  • comparing ladder state against simulated equipment state,
  • and revising the implementation after abnormal behavior appears.

A useful test case is a coupled process such as flow and tank pressure or level and temperature. Inject a step change in one manipulated variable, then verify whether the predicted state update tracks the simulated process response without runaway oscillation, saturation, or implausible cross-coupling.

This is where Simulation-Ready should be defined properly. A Simulation-Ready engineer is not merely someone who can write valid PLC syntax. It is an engineer who can prove, observe, diagnose, and harden control logic against realistic process behavior before it reaches a live process. Syntax is easy to admire. Deployability is less forgiving.

What should you document as engineering evidence?

If you want to demonstrate competence in advanced PLC logic, build a compact body of engineering evidence rather than a screenshot gallery.

Use this structure:

  • Define the process, states, manipulated variables, and control objective.

- State what acceptable behavior means in measurable terms: settling time, bounded overshoot, no watchdog fault, stable state update, correct interlock behavior.

  • Show the implemented rungs, relevant tags, and the corresponding simulated plant response.
  • Record the disturbance, bad coefficient, sensor failure, saturation event, or timing stress introduced.
  • Explain what logic, scheduling, scaling, or data-type change was applied.
  • State what the failure revealed about the model, the implementation, or the controller limits.
  1. System Description
  2. Operational definition of “correct”
  3. Ladder logic and simulated equipment state
  4. The injected fault case
  5. The revision made
  6. Lessons learned

That structure is more valuable than a polished screenshot because it demonstrates engineering judgment under constraint. Employers and reviewers generally care less about whether the rung looked tidy than whether you knew what to do when the model misbehaved.

When should you keep MPC math in the PLC, and when should you not?

MPC math belongs in the PLC only when the controller, task structure, and process dynamics support it. The migration of advanced control toward edge and local execution is real, but that does not mean every PLC should become a small, overworked DCS.

Keep the calculation in the PLC when these conditions are true:

  • the matrix dimensions are modest,
  • the execution time is bounded and tested,
  • the process benefits from local deterministic response,
  • maintenance teams can support the implementation,
  • and validation has shown stable behavior under realistic disturbances.

Move the calculation to a DCS, industrial PC, or edge compute layer when these conditions dominate:

  • larger optimization horizons,
  • heavier matrix operations,
  • frequent model updates,
  • constrained PLC resources,
  • or unacceptable scan-time impact.

The engineering question is not whether PLC-based MPC is fashionable. It is whether the implementation is auditable, deterministic, and supportable on the target hardware. Those are less glamorous words than “AI” or “optimization.” They also keep plants running.

What standards and literature matter when evaluating this approach?

This implementation sits across control theory, PLC execution constraints, simulation practice, and safety-adjacent engineering discipline. No single standard tells you how to write matrix multiplication in ladder, but several bodies of literature and standards shape the correct boundaries.

Relevant references include:

  • IEC 61131-3
  • Governs PLC programming languages such as Ladder Diagram and Structured Text.
  • IEC 61508
  • Provides the broader framework for functional safety of electrical/electronic/programmable electronic systems.
  • exida guidance and safety lifecycle literature
  • Useful for understanding proof, validation discipline, and the separation between functional behavior and safety claims.
  • IFAC and process control literature
  • Relevant for MPC architecture, state-space modeling, and constrained optimization.
  • Digital twin and simulation training literature
  • Relevant for validating logic against realistic plant behavior and improving commissioning readiness.

A necessary boundary: validating control logic in simulation does not by itself establish SIL suitability, regulatory compliance, or site competence. It improves pre-deployment evidence. It does not abolish the rest of engineering.

Keep exploring

Interlinking

References

Editorial transparency

This blog post was written by a human, with all core structure, content, and original ideas created by the author. However, this post includes text refined with the assistance of ChatGPT and Gemini. AI support was used exclusively for correcting grammar and syntax, and for translating the original English text into Spanish, French, Estonian, Chinese, Russian, Portuguese, German, and Italian. The final content was critically reviewed, edited, and validated by the author, who retains full responsibility for its accuracy.

About the Author:PhD. Jose NERI, Lead Engineer at Ampergon Vallis

Fact-Check: Technical validity confirmed on 2026-03-23 by the Ampergon Vallis Lab QA Team.

Ready for implementation

Use simulation-backed workflows to turn these insights into measurable plant outcomes.

© 2026 Ampergon Vallis. All rights reserved.
|