---
url: /dyad/dev/tutorials/discretizing-linear-systems.md
description: >-
  Using c2d from ControlSystems.jl to turn a continuous-time controller into a
  discrete-time Dyad component.
---

# Discretizing Continuous-Time Linear Systems {#discretizing-linear-systems}

Control design is often done in continuous time, but a controller that runs on a computer is running in discrete time. This page covers converting between the two with [ControlSystems.jl](https://juliacontrol.github.io/ControlSystems.jl/dev/) and making use of the result in a clocked Dyad model.

See [Discrete-Time Modeling](/tutorials/discrete-time-modeling#discrete-time-modeling) for clocks, and [Array Variables in Clocked Components](/tutorials/discrete-arrays#discrete-arrays) for the discrete linear-system components.

## `c2d` and the choice of method {#c2d-and-the-choice-of-method}

`c2d(sys, Ts, method)` converts a continuous-time system to a periodic discrete-time system at sample interval `Ts`. `d2c` converts in the other direction. The discretization methods differ in what they preserve:

|      Method |                                                                                               Preserves |                                                                          Use when |
| -----------:| -------------------------------------------------------------------------------------------------------:| ---------------------------------------------------------------------------------:|
|      `:zoh` |               The response to a piecewise-constant input, exactly. State components keep their meaning. |  Often used when discretizing a **plant model** driven through a zero-order hold. |
|      `:foh` |                                      The response to a piecewise-linear input. State meaning preserved. |                          The input is better modelled as ramping between samples. |
|   `:tustin` | The frequency response, approximately, with no aliasing of the imaginary axis. Changes the state basis. |                                 Commonly used when discretizing a **controller**. |
| `:fwdeuler` |                                                      No specific property; this is the simplest method. | Approximations at sample rates far above the dynamics. Generally not recommended. |

`:tustin` (the bilinear transform) accepts `w_prewarp`, which makes the discrete-time and continuous-time frequency responses agree exactly at that frequency instead of only at DC — useful when a specific crossover or notch frequency matters.

A common guideline is: **ZoH for plant models, Tustin for controllers.** ZoH matches what the hardware actually does to a plant input, while Tustin gives the controller the frequency-domain behaviour it was designed for.

## Getting the coefficients into a Dyad component {#Getting-the-coefficients-into-a-Dyad-component}

[`DiscreteTransferFunction`](../stdlib/DiscreteComponents/components/DiscreteTransferFunction.md) takes numerator and denominator coefficient arrays `b` and `a`, in the format that ControlSystems.jl's `numvec`/`denvec` return — descending powers of $z$, without reordering or rescaling. The structural parameters `nb` and `na` must be set to the lengths of these arrays. A numerator shorter than the denominator is right-aligned, as in `tf(num, den, Ts)`, so the component is strictly proper and its output does not depend on the current input. The coefficients are ordinary parameters and can be changed without recompiling the model.

Discretizing a PI controller $C(s) = K\left(1 + \dfrac{1}{T_i s}\right)$ with $K = 2$, $T_i = 0.5$ at $T_s = 0.05$ using Tustin:

```julia
using ControlSystemsBase

Ts = 0.05
K, Ti = 2.0, 0.5
C  = K * (1 + tf(1.0, [Ti, 0.0]))
Cz = c2d(ss(C), Ts, :tustin)

b = numvec(tf(Cz))[1]
a = denvec(tf(Cz))[1]
(b, a)
```

```ansi
([2.1, -1.9000000000000001], [1.0, -1.0])
```

These two vectors are passed unchanged to the component. The plant is discretized with ZoH for comparison:

```julia
P  = ss(tf(1.0, [0.5, 1.0]))
Pz = c2d(P, Ts, :zoh)
(numvec(tf(Pz))[1], denvec(tf(Pz))[1])
```

```ansi
([0.09516258196404037], [1.0, -0.9048374180359594])
```

## A closed loop built from discretized designs {#A-closed-loop-built-from-discretized-designs}

Both blocks below carry the coefficients computed above.
Download as a Dyad projectc2d.zipOpen in Dyad Studio›

```dyad
"""
Discrete-time PI controller (Tustin) driving a discrete-time plant (ZoH), with the
coefficients taken from `c2d`. Both blocks run on the same clock.
"""
test component DiscretizedLoop
  ref = BlockComponents.Sources.Step(height = 1.0, start_time = 0.1)
  ref_sampler = DiscreteComponents.Sampler()
  clock = DiscreteComponents.PeriodicClock(dt = 0.05)
  err = BlockComponents.Math.Add(k2 = -1)
  "PI controller, c2d(..., :tustin)"
  ctrl = DiscreteComponents.DiscreteTransferFunction(nb = 2, na = 2, b = [2.1, -1.9], a = [1.0, -1.0])
  "Plant, c2d(..., :zoh)"
  plant = DiscreteComponents.DiscreteTransferFunction(
      nb = 1, na = 2, b = [0.09516258196404037], a = [1.0, -0.9048374180359594])
relations
  connect(ref.y, ref_sampler.u)
  connect(ref_sampler.y, clock.y, err.u1)
  connect(err.y, ctrl.u)
  connect(ctrl.y, plant.u)
  connect(plant.y, err.u2)
end

analysis DiscretizedLoopAnalysis
  extends TransientAnalysis(stop = 2.0)
  model = DiscretizedLoop()
end
```

```julia
using Plots
using DyadInterface
result = DiscretizedLoopAnalysis()
model = artifacts(result, :SimplifiedSystem)
p1 = plot(result; idxs = model.plant.y, title = "Plant output")
p2 = plot(result; idxs = model.ctrl.y, title = "Control signal")
plot(p1, p2; layout = (2, 1), legend = false, xlabel = "t",
     size = (600, 430), plot_title = "Loop assembled from c2d designs")
```

![](xbojnus.svg)

The same loop can be evaluated in Julia before it is built in Dyad, which provides a direct way to verify the discretization:

```julia
Lz = Cz * Pz
Tz = feedback(Lz)
res = step(Tz, 2.0)
plot(res.t, vec(res.y); seriestype = :steppost, legend = false,
     xlabel = "t", title = "Same loop, evaluated with ControlSystems.jl")
```

![](ygomzhf.svg)

## Discretization inside components {#Discretization-inside-components}

Some components do their own discretization rather than taking coefficients. The integrating and differentiating blocks take a `DiscretizationMethod`:

* `Forward()` — forward Euler, $T_s/(z-1)$

* `Backward()` — backward Euler, $T_s z/(z-1)$, the default

* `Trapezoidal()` — $(T_s/2)(z+1)/(z-1)$, the same bilinear rule as `c2d(..., :tustin)`

[`DiscreteIntegrator`](../stdlib/DiscreteComponents/components/DiscreteIntegrator.md) takes `method`, and the discrete-time PID blocks take `Imethod` and `Dmethod` separately, a discrete-time PID controller commonly uses forward Euler on the integral term and backward Euler on the derivative term.

Choosing `Trapezoidal` there is equivalent to designing the term in continuous time and applying `c2d(..., :tustin)` to it.

## Discretizing noise covariance {#Discretizing-noise-covariance}

When a state estimator is discretized, the process-noise covariance has to be converted too — using a continuous-time `Qc` unchanged in a discrete-time filter gives an incorrect noise level, and the error depends on `Ts`. `c2d` has methods for this:

```julia
Qd     = c2d(sys::StateSpace{Continuous}, Qc, Ts)
Qd, Rd = c2d(sys::StateSpace{Discrete}, Qc, Rc; opt = :c)
```

See the [`c2d` documentation](https://juliacontrol.github.io/ControlSystems.jl/dev/lib/constructors/#ControlSystemsBase.c2d) for the assumptions behind each form, in particular how a rank-deficient `Qc` is handled.

Several DyadControlSystems analyses discretize the plant internally and expose the sample interval as an argument, so you do not always have to do this yourself — see [Pole placement](../analyses/pole_placement.md), [LQG analysis](../analyses/lqg_analysis.md) and [State estimation](../analyses/state_estimation_analysis.md).

## See also {#See-also}

* [Discrete-Time Modeling](/tutorials/discrete-time-modeling#discrete-time-modeling) — clocks, partitions and reading results

* [Sampled-Data Systems](/tutorials/sampled-data#sampled-data) — combining discrete-time and continuous-time models

* [Array Variables in Clocked Components](/tutorials/discrete-arrays#discrete-arrays) — `DiscreteTransferFunction` and `DiscreteStateSpace`

* [Frequency-response analysis](../analyses/frequency_response.md) — measuring the loop you built

* [ControlSystems.jl: Analysis of sampled-data systems](https://juliacontrol.github.io/ControlSystems.jl/dev/examples/zoh/) — how ZoH interacts with continuous-time analysis

* [ControlSystems.jl: Performance considerations](https://juliacontrol.github.io/ControlSystems.jl/dev/man/numerical/) — numerical caveats when discretizing

* [RobustAndOptimalControl.jl](https://juliacontrol.github.io/RobustAndOptimalControl.jl/dev/) and [DyadControlSystems](https://help.juliahub.com/dyad/DyadControlSystems.jl/dev/) — the design side
