---
url: /dyad/stable/tutorials/discrete-arrays.md
description: >-
  Working with array-valued clocked variables, array connectors and
  discrete-time state-space models in Dyad.
---

# Array Variables in Clocked Components {#discrete-arrays}

Clocked variables and connectors may be arrays, which is what makes shift registers, MIMO discrete-time systems and vector-valued discrete logic expressible. This page collects the usage patterns and the current limitations.

See [Discrete-Time Modeling](/tutorials/discrete-time-modeling#discrete-time-modeling) for clocks and shift operators, [Arrays](/manual/syntax#syntax-arrays) for array syntax in general, and [Clocks](/manual/syntax#syntax-clocks) for the clock-annotation grammar.

## Array-valued clocked variables {#Array-valued-clocked-variables}

An array variable is declared as usual, and each element may carry its own clocked equation. The dimension must be a literal or a `structural parameter`.

The canonical use is a **shift register**: element 1 takes the current input and every other element takes the previous value of its neighbour. Averaging the register gives a moving-average filter:
Download as a Dyad projectdiscretearrays.zipOpen in Dyad Studio›

```dyad
"""
Moving average over the last `N` samples, implemented as an array-valued shift
register, with a whole-array initial condition at shift -1.
"""
component WindowAverage@[input clk extends Discrete]
  "Input signal"
  u = Dyad.RealInput@[clk]()
  "Averaged output"
  y = Dyad.RealOutput@[clk]()
  "Number of samples to average over"
  structural parameter N::Integer = 4
  "The shift register"
  variable taps::Real[N]
relations
  taps[1]@clk = u@clk
  for i in 2:N
    taps[i]@clk = taps[i - 1]@(clk-1)
  end
  initial taps@(clk-1) = fill(0.0, N)
  y = sum(taps) / N
end
```

Two things to note. The `for` loop is unrolled at compile time, because `N` is a `structural parameter` — this is `N-1` equations, not a runtime loop. And `sum` works directly on the symbolic array.

The **initial condition is not optional.** Omitting it fails with

```
An initialization equation is required for every shifted variable; missing:
  avg₊taps(t) at shift -1: add `avg₊taps(k - 1) ~ ...` to `initialization_eqs`
```

It may be given for the array as a whole, as above, or element by element with `for i in 1:N initial taps[i]@(clk-1) = 0.0 end`.

The library's [`MovingAverageFilter`](../stdlib/DiscreteComponents/components/MovingAverageFilter.md) is this component, with an `initialization` parameter instead of a hard-coded zero — see [Initializing Discrete-Time Components](/tutorials/discrete-initialization#discrete-initialization). Use it instead of writing a custom component; `WindowAverage` is included here to illustrate the array mechanics. [`FIRFilter`](../stdlib/DiscreteComponents/components/FIRFilter.md) generalizes the same structure to an arbitrary coefficient vector.

Wiring it to a sampled noisy sine shows the smoothing:

```dyad
"""
`WindowAverage` smoothing a noisy sampled sine.
"""
test component WindowAverageDemo
  source = BlockComponents.Sources.Sine(amplitude = 1.0, frequency = 1.0)
  sampling = DiscreteComponents.SampleWithADEffects(sigma = 0.15, quantized = false)
  clock = DiscreteComponents.PeriodicClock(dt = 0.02)
  avg = WindowAverage(N = 8)
relations
  connect(source.y, sampling.u)
  connect(sampling.y, clock.y, avg.u)
end

analysis WindowAverageDemoAnalysis
  extends TransientAnalysis(stop = 2.0)
  model = WindowAverageDemo()
end
```

```julia
using Plots
using DyadInterface
result = WindowAverageDemoAnalysis()
model = artifacts(result, :SimplifiedSystem)
p1 = plot(result; idxs = model.sampling.y, title = "Noisy samples")
p2 = plot(result; idxs = model.avg.y, title = "Moving average")
plot(p1, p2; layout = (2, 1), legend = false, xlabel = "t", ylabel = "Signal",
     size = (600, 420),
     plot_title = "Array shift register as a moving-average filter")
```

![](smgaciy.svg)

## Whole-array equations {#Whole-array-equations}

An equation may also be written for an entire array at once, with matrix–vector products on the right-hand side. This is how [`DiscreteStateSpace`](../stdlib/DiscreteComponents/components/DiscreteStateSpace.md) expresses a linear system:

```dyad
  x@clk = A * x@(clk-1) + B * (u@clk - u0)
  if with_D
    y@clk = C * x@(clk-1) + D * (u@clk - u0) + y0
  else
    y@clk = C * x@(clk-1) + y0
  end
```

Remember the negative-shift convention: `x@(clk-1)` is the current value of the state vector and `x@clk` is its next value, which is being computed, so these lines are $x(k+1) = Ax(k) + B(u(k) - u_0)$ and $y(k) = Cx(k) + D(u(k) - u_0) + y_0$. The structural parameter `with_D` selects whether the feedthrough term is present; see [Discrete state-space blocks](/tutorials/discrete-arrays#discrete-arrays-state-space).

## Array connectors {#Array-connectors}

A component can expose a vector of connectors by building them with a comprehension. `DiscreteStateSpace` does this for its inputs and outputs:

```dyad
component DiscreteStateSpace@[input clk extends Discrete]
  u = [RealInput@[clk]() for i in 1:nu] {^u}
  y = [RealOutput@[clk]() for i in 1:ny] {^y}
  structural parameter nx::Integer = 2
  structural parameter nu::Integer = 1
  structural parameter ny::Integer = 1
  parameter A::Real[nx, nx] = fill(0.0, nx, nx)
  parameter B::Real[nx, nu] = fill(1.0, nx, nu)
  parameter C::Real[ny, nx] = fill(1.0, ny, nx)
  structural parameter with_D::Boolean = true
  parameter D::Real[ny, nu] = fill(0.0, ny, nu)
  variable x::Real[nx]
  ...
end
```

Individual elements are then connected as `connect(src.y, ss.u[1])`.

### Writing matrix literals {#Writing-matrix-literals}

Dyad array literals are comma-separated, and a matrix is a list *of rows* — there is no MATLAB-style `;` row separator or space-separated column syntax. A $2 \times 2$ matrix, a column vector and a row vector are written:

```dyad
parameter A::Real[2, 2] = [[0.9, 0.05], [0.0, 0.85]]
parameter B::Real[2, 1] = [[0.0], [0.1]]
parameter C::Real[1, 2] = [[1.0, 0.0]]
```

Writing `[0.9 0.05; 0.0 0.85]` instead is a parse error. `fill` is available for uniform matrices, which is how the default values of `DiscreteStateSpace` are written (`fill(0.0, nx, nx)`).

### Array initial conditions {#Array-initial-conditions}

Vector-valued state uses the array variants of the initialization enum, `InitialStateArray(x0)` and `InitialOutputArray(y0)` — see [Initializing Discrete-Time Components](/tutorials/discrete-initialization#discrete-initialization) for the scalar counterparts. Components with array state generally *reject* the scalar variants, and vice versa, because the shapes cannot be reconciled. [`FIRFilter`](../stdlib/DiscreteComponents/components/FIRFilter.md) is an exception: it is a scalar component, and its `InitialStateArray(x0)` variant specifies the input history sample by sample.

## Discrete state-space blocks {#discrete-arrays-state-space}

[`DiscreteStateSpace`](../stdlib/DiscreteComponents/components/DiscreteStateSpace.md) combines everything above — array connectors, array state, whole-array equations and array initial conditions — into a MIMO linear block:

```dyad
ss = DiscreteComponents.DiscreteStateSpace(
    nx = 2, nu = 1, ny = 1,
    A = [[0.9, 0.05], [0.0, 0.85]],
    B = [[0.0], [0.1]],
    C = [[1.0, 0.0]],
    with_D = false,
    initialization = DiscreteComponents.InitialCondition.InitialStateArray(x0 = [0.5, 0.0]))
```

With `with_D = false` the system is strictly proper: `D` is ignored, and the output does not depend structurally on the current input. This is required when the block closes a loop on the same clock with a component that has direct feedthrough, such as a controller, since the two feedthrough paths would otherwise form a same-tick algebraic loop. A `D` matrix whose entries are zero still creates this dependency.

## Reading array results {#Reading-array-results}

Indexing a solution with a vector-valued clocked variable returns a vector of vectors, one entry per sample. Flatten it into a matrix when you want to work with it numerically:

```julia
sol = artifacts(result, :RawSolution)
X = reduce(hcat, sol[model.avg.taps])   # N × number-of-samples
```

Individual elements can be indexed directly, e.g. `model.avg.taps[1]`. See [Reading results](/tutorials/discrete-time-modeling#discrete-time-reading-results) for the clocked-variable time grid.

## Limitations {#Limitations}

* **A clock cannot be attached to an array connection.** A clock output is scalar, so a `PeriodicClock` must be connected to a scalar signal in the partition — as in the example above, where the clock joins the sampler output rather than an array port.

* **A clocked array read at a negative shift needs an initial condition.** There is no implicit zero; write, for example, `initial taps@(clk-1) = fill(0.0, N)`.

* **An element equation cannot read another element of the same array at the same tick.** The equations of a clocked partition define the entire array at once at each tick, so `x[2]@clk = x[1]@clk + 1` is rejected with `CausalityError: Combinational cycle detected`. Use separate scalar variables, or read the previous tick, `x[1]@(clk-1)`.

* **An array element cannot be assigned at an index computed at run time.** For the same reason, a single store at a varying index, as in a ring buffer, is rejected. A ring buffer can be implemented with a registered Julia function that returns the updated array, or with one conditional assignment per element.

* **Use floating-point literals in array element equations.** Writing `0` rather than `0.0` in an equation for one element of a `Real` array leaves the array with mixed element types. Simulation is not affected, but export as C fails with `Non-isbits type SynchArray{Float64, 1} … not supported for C lowering`. Write `0.0`.

## 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

* [Initializing Discrete-Time Components](/tutorials/discrete-initialization#discrete-initialization) — the initialization enum, including the array variants

* [Arrays](/manual/syntax#syntax-arrays) and [Clocks](/manual/syntax#syntax-clocks) — syntax reference

* [`DiscreteStateSpace`](../stdlib/DiscreteComponents/components/DiscreteStateSpace.md) and [`MovingAverageFilter`](../stdlib/DiscreteComponents/components/MovingAverageFilter.md) — the components shown here

* [ControlSystems.jl](https://juliacontrol.github.io/ControlSystems.jl/dev/) — building the `A`, `B`, `C`, `D` matrices for a discrete-time design
