Convolution
What is convolution?
Convolution is a way of combining two signals into a third: one signal, the kernel, is flipped, slid along the other, and at each position the overlapping values are multiplied and summed. It's how a filter, a blur, an echo or any linear system turns an input into an output, and it's written with an asterisk: .

A noisy sine convolved with a seven-sample moving average: the input (top), the kernel slid to one position (middle) and the smoothed output (bottom). Try the interactive calculator.
- Convolution is a sliding weighted sum: flip the kernel, slide it, multiply, add.
- A system's impulse response is its kernel: convolve any input with it to get the system's output.
- Convolving N samples with M samples gives N + M − 1 output samples.
- The convolution theorem: convolution in time is multiplication in frequency, so the FFT makes long convolutions fast.
- Cross-correlation is the same calculation without the flip; it finds patterns rather than modelling systems.
How convolution works: flip, slide, multiply and sum
Think of the kernel as a set of weights, and the output as a weighted average of the input around each point. Four steps give one output sample, :
- Flip the kernel, so its first sample is on the right.
- Slide it along the input until its last sample sits under position .
- Multiply each kernel value by the input value directly above it.
- Sum the products. That total is .
Then move one sample to the right and repeat, for every position where the kernel and the input overlap.
Why is the kernel flipped?
Because the kernel is usually an impulse response: the output a system gives when the input is a single spike of height 1 (a unit impulse). Its first sample, , is the system's immediate reaction, is what's left one sample later, and so on. The output now, , is the present input times , plus the previous input times , plus the one before that times . Writing that as a sum over the inputs puts the kernel in reverse order, and that reversal is the flip.
Any linear, time-invariant (LTI) system, such as an audio filter, a spring and damper, a room's acoustics or an RC circuit, is completely described by its impulse response. Measure that once, and you can work out the output for any input by convolution.
The moving average is a familiar case. A kernel of five equal weights, each 1/5, replaces every sample with the mean of it and the four before it. That's a convolution, and it's why moving averages smooth noise: each output blends several noisy inputs. Change the weights and you change the filter: a bell-shaped (Gaussian) kernel smooths more gently, a decaying kernel favours recent samples, and a kernel of subtracts each sample's neighbour, which picks out sudden jumps.
The convolution formula
Discrete convolution, for sampled signals such as audio, sensor readings or prices:
The sum runs over every , but in practice only the values of where both and exist contribute. Here is the kernel flipped (the ) and shifted by .
Continuous convolution, the convolution integral, for functions of continuous time:
It's the same idea with an integral in place of the sum: is flipped, shifted by , multiplied by , and the area under the product is the output at . The dummy variable plays the role of .
If has samples and has , the full convolution has
samples. The output starts as soon as the kernel's leading edge touches the input, and ends when its trailing edge leaves it. A 1,000-sample signal and a filter with 31 coefficients (or taps) give 1,030 output samples.
Near the ends, the kernel overhangs the input, and the missing samples are treated as zeros. Libraries usually offer three output sizes: full (all samples), same (the middle , aligned with the input) and valid (only the samples where the kernel lies entirely over real data).
Convolution example, step by step
Convolve with . Both have 3 samples, so the output has .
| n | Flipped kernel lined up under x | Products | y[n] |
|---|---|---|---|
| 0 | only h[0] overlaps x[0] | 1 × 0 | 0 |
| 1 | h[1] under x[0], h[0] under x[1] | 1 × 1 + 2 × 0 | 1 |
| 2 | h[2] under x[0], h[1] under x[1], h[0] under x[2] | 1 × 0.5 + 2 × 1 + 3 × 0 | 2.5 |
| 3 | h[2] under x[1], h[1] under x[2] | 2 × 0.5 + 3 × 1 | 4 |
| 4 | only h[2] overlaps x[2] | 3 × 0.5 | 1.5 |
So .
Two quick checks:
- Sum check: the output's total equals the product of the inputs' totals. Here , and .
- Shape check: this kernel is "nothing now, all of it one sample later, half of it two samples later". The output is the input delayed by one sample, plus half of it delayed by two.
Properties of convolution
Convolution behaves like multiplication: order and grouping don't matter, and it spreads over addition.
| Property | Formula | What it means in practice |
|---|---|---|
| Commutative | It doesn't matter which one you call the kernel | |
| Associative | Two filters in a row act like one filter whose kernel is | |
| Distributive | Two filters side by side, outputs added, act like one filter with kernel | |
| Identity | Convolving with a unit impulse changes nothing | |
| Shift | A kernel that is a single impulse at is a pure delay of samples | |
| Linearity | Scale or add inputs and the outputs scale and add the same way | |
| Sum | A kernel that sums to 1 keeps the signal's average level |
The associative property is why a chain of filters can be designed, analysed or applied as one. The identity property is also a handy test: feed a unit impulse into any linear system, and what comes out is its kernel.
The convolution theorem
The convolution theorem links convolution to the Fourier transform. Writing for the Fourier transform:
Convolution in time is multiplication in frequency, and the reverse holds too: multiplication in time is convolution in frequency.
The Fourier transform of a kernel is its frequency response: how much it lets through at each frequency. Convolving with the kernel multiplies the signal's spectrum by that response. A moving-average kernel has a response that is high at low frequencies and small at high ones, so it acts as a low-pass filter. A difference kernel such as does the opposite, a simple high-pass filter.
Fast convolution with the FFT
Direct convolution needs about multiplications. With the fast Fourier transform (FFT), you can instead:
- Zero-pad and to the same length , at least (usually rounded up to a power of 2).
- Take the FFT of both.
- Multiply the two spectra, bin by bin.
- Take the inverse FFT, and keep the first samples.
Adapted from Burnett-Thompson (2007).
That costs on the order of operations instead of , so the saving grows with the kernel's length. In Smith's measurements, FFT convolution overtook direct convolution once the kernel was about 40 to 80 samples long, depending on the hardware. For signals that never end, such as live audio, the overlap-add method splits the input into blocks, convolves each with the FFT and adds the overlapping tails.
Zero-pad both signals, or the output wraps around. Multiplying DFTs (the discrete Fourier transform an FFT computes) gives circular convolution, in which the tail that should run past the end lands on top of the start. Padding to at least samples leaves room for the tail, so circular convolution gives the same answer as ordinary (linear) convolution.
Convolution vs cross-correlation and circular convolution
Cross-correlation is convolution without the flip, and circular convolution is convolution with the ends wrapped round.
| Convolution | Cross-correlation | Circular convolution | |
|---|---|---|---|
| Formula | (one common convention) | Like convolution, with indices wrapped modulo | |
| Kernel flipped? | Yes | No | Yes |
| Commutative? | Yes | No: swapping the signals reverses the result | Yes |
| Output length | lags | (wraps around) | |
| Answers | What does this system do to this signal? | Where, and at what delay, does this pattern appear? | The result of multiplying unpadded FFTs |
| Used for | Filters, smoothing, echo, blur, system modelling | Template matching, time-delay estimation, radar, sonar | Fast convolution via the FFT, periodic signals |
For a symmetric kernel, such as a moving average or a Gaussian, the flip changes nothing, so convolution and cross-correlation give the same result. For an asymmetric one they differ: cross-correlating with gives at lags to , not the convolution's . Cross-correlating a signal with itself is autocorrelation, which reveals repeating patterns.
What convolution is used for
Convolution is how any linear, time-invariant system acts on a signal, so it turns up in every kind of filtering.
- Filtering: every FIR (finite impulse response) filter is a convolution with its kernel. Low-pass filters remove noise; high-pass filters remove drift.
- Smoothing: moving averages, Gaussian smoothing and exponential smoothing of sensor data, prices and measurements.
- Echo and reverb: an echo is a kernel with a spike now and a smaller one later. Convolution reverb records a real room's impulse response and convolves dry audio with it.
- Images: the same operation in two dimensions, with a small grid of weights: a 3 × 3 grid of 1/9 blurs; kernels with positive and negative weights find edges or sharpen.
- Neural networks: convolutional neural networks (CNNs) slide many small 2D kernels over images and learn the weights. It's the same sliding multiply-and-sum, though most libraries skip the flip and compute cross-correlation.
- Probability: add two independent random quantities, such as two dice, and the distribution of the total is their two distributions convolved. Repeat it many times and the result tends to a bell curve.
- Physics and engineering: the response of any LTI system, such as a circuit, a sensor or a building in an earthquake, is its input convolved with its impulse response. Instruments blur what they measure in the same way, and deconvolution tries to undo it.
Common convolution mistakes
Most convolution mistakes are about the flip, the length and edges of the output, or the cost of long kernels.
- Forgetting the flip. Sliding the kernel without reversing it computes cross-correlation. With symmetric kernels nobody notices; with an echo or a derivative kernel the result is mirrored.
- Expecting the output to be as long as the input. Full convolution adds samples. Decide whether you want full, same or valid output before you compare or plot results.
- Ignoring the delay. A causal kernel (one that uses only past samples) delays the signal. A symmetric kernel of taps delays it by samples, so smoothed lines appear shifted to the right unless you align them.
- Kernels that don't sum to 1. A smoothing kernel that sums to 2 doubles the signal's level. Normalise it, unless the gain is intended.
- Treating the edges as real data. The first and last output samples include padded zeros, so a smoothing kernel's output dips towards zero there. Trim them, or pad with repeated or mirrored values instead.
- FFT convolution without zero-padding. Multiplying unpadded FFTs gives circular convolution, and the end of the output wraps onto its start.
- Direct convolution with very long kernels. grows quickly. For kernels longer than a few dozen samples, try the FFT method.
How to calculate and chart a convolution in JavaScript, React or Angular
The calculator below convolves an input (48 samples for the built-in signals) with the kernel you choose and charts the input, the kernel and the result on stacked axes. SciChart.js computes the output itself: an XyCustomFilter convolves the input series with the kernel and recalculates whenever the input changes.
- Pick an input and a kernel, and set the kernel's width (for the echo, its delay).
- Move Slide n, or press Play, to slide the flipped kernel along the input: the ringed output sample is the sum shown above the chart.
- Choose Your numbers to convolve any two short sequences, such as the worked example above: the full result is listed when it has 16 values or fewer.
- Hover for values, scroll to zoom, drag to pan and double-click to reset.
Here is the code for this chart. The convolution itself is the convolveAt function inside the two XyCustomFilters; the rest builds the lanes and the controls' results line:
- JavaScript
- React
- Angular
// Convolution calculator: the input, the kernel and the output, y = x * h, in three lanes.
// Signals and kernels are arrays of numbers. SciChart.js computes the output with an XyCustomFilter.
// The products that make up one output sample y[n], for showing the working
function productsAt(x, h, n) {
const terms = [];
for (let k = Math.max(0, n - h.length + 1); k <= Math.min(n, x.length - 1); k++) {
terms.push({ k, x: x[k], h: h[n - k] });
}
return terms;
}
// Kernels (impulse responses). The smoothing kernels add up to 1, so they keep the signal's level.
const sumTo1 = (h) => {
const total = h.reduce((a, b) => a + b, 0);
return h.map((v) => v / total);
};
// Moving average: w equal weights
const movingAverageKernel = (w) => new Array(w).fill(1 / w);
// Gaussian: a bell-shaped weighted average, w samples wide
const gaussianKernel = (w) => {
const sigma = Math.max(w / 6, 0.4);
const centre = (w - 1) / 2;
return sumTo1(Array.from({ length: w }, (_, k) => Math.exp(-0.5 * ((k - centre) / sigma) ** 2)));
};
// Exponential decay: recent samples count most, like an RC low-pass filter or a fading memory
const exponentialDecayKernel = (w) => {
const ratio = w > 1 ? Math.pow(0.05, 1 / (w - 1)) : 0; // the last weight is 5% of the first
return sumTo1(Array.from({ length: w }, (_, k) => Math.pow(ratio, k)));
};
// Echo: the sound now, plus a copy at half the volume d samples later
const echoKernel = (d) => {
const h = new Array(d + 1).fill(0);
h[0] = 1;
h[d] = 0.5;
return h;
};
// Difference (edge detector): y[n] = x[n] - x[n - 1], large where the signal jumps
const differenceKernel = () => [1, -1];
// Example input signals, 48 samples each. The noise uses a seeded random generator, so it is the same every time.
const SIGNAL_LENGTH = 48;
function makeInput(type) {
let seed = 11;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
return Array.from({ length: SIGNAL_LENGTH }, (_, n) => {
if (type === "step") return n >= 12 ? 1 : 0;
if (type === "pulse") return n >= 12 && n < 24 ? 1 : 0;
if (type === "impulse") return n === 8 ? 1 : 0;
// noisy sine: one cycle every 24 samples, plus noise
return Math.sin((2 * Math.PI * n) / 24) + 0.6 * (random() + random() - 1);
});
}
// Reads "1, 2, 3" (commas or spaces) into [1, 2, 3], ignoring anything that isn't a number
const parseNumbers = (text) =>
text
.split(/[\s,;]+/)
.filter((part) => part !== "")
.map(Number)
.filter((v) => Number.isFinite(v))
.slice(0, 64);
async function convolutionCalculator(divElementId) {
const {
SciChartSurface,
NumericAxis,
FastImpulseRenderableSeries,
XyScatterRenderableSeries,
XyDataSeries,
XyCustomFilter,
EllipsePointMarker,
NumberRange,
EAutoRange,
EAxisAlignment,
LeftAlignedOuterVerticallyStackedAxisLayoutStrategy,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
const INPUTS = [
{ key: "noisy", label: "Noisy sine" },
{ key: "step", label: "Step" },
{ key: "pulse", label: "Pulse" },
{ key: "impulse", label: "Impulse" },
{ key: "custom", label: "Your numbers" }
];
const KERNELS = [
{ key: "average", label: "Moving average", make: movingAverageKernel },
{ key: "gaussian", label: "Gaussian", make: gaussianKernel },
{ key: "decay", label: "Exponential decay", make: exponentialDecayKernel },
{ key: "echo", label: "Echo", make: echoKernel },
{ key: "difference", label: "Difference [1, −1]", make: differenceKernel },
{ key: "custom", label: "Your numbers" }
];
const root = document.getElementById(divElementId);
const controls = addControls(root, { inputs: INPUTS, kernels: KERNELS, onChange: (state) => update(state) });
const { wasmContext, sciChartSurface } = await SciChartSurface.create(controls.chartDiv, {
theme: new SciChartJsNavyTheme()
});
const xAxis = new NumericAxis(wasmContext, {
axisTitle: "Sample index (k, n)",
autoRange: EAutoRange.Never,
labelPrecision: 0,
drawMinorGridLines: false
});
sciChartSurface.xAxes.add(xAxis);
// Three lanes, top to bottom: the input, the flipped and shifted kernel, and the output
sciChartSurface.layoutManager.leftOuterAxesLayoutStrategy = new LeftAlignedOuterVerticallyStackedAxisLayoutStrategy();
const lanes = [
{ id: "x", title: "Input x[k]", color: "#50C7E0" },
{ id: "h", title: "Kernel h[n−k]", color: "#F48420" },
{ id: "y", title: "Output y[n]", color: "#3BD16F" }
];
lanes.forEach((lane) =>
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
id: lane.id,
axisAlignment: EAxisAlignment.Left,
axisTitle: lane.title,
axisTitleStyle: { color: lane.color, fontSize: 13 },
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.15, 0.15),
maxAutoTicks: 5,
labelPrecision: 2,
drawMinorGridLines: false
})
)
);
// Stem (impulse) series: one vertical line and dot per sample
const addStems = (yAxisId, dataSeries, color, opacity = "") =>
sciChartSurface.renderableSeries.add(
new FastImpulseRenderableSeries(wasmContext, {
yAxisId,
dataSeries,
stroke: color + opacity,
fill: color + opacity,
strokeThickness: 2,
size: 7
})
);
// The input x, padded with M - 1 zeros so the output can run on past its end (N + M - 1 samples in all)
const inputSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Input x[k]" });
addStems("x", inputSeries, "#50C7E0");
// The kernel, flipped and slid to the current position n
const kernelSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Kernel h[n−k]" });
addStems("h", kernelSeries, "#F48420");
// The output y = x * h, computed by SciChart.js from the input series with an XyCustomFilter.
// SciChart calls filterFunction(n) for every sample when the input is replaced, and only for the new
// samples when you append to it, so the same code keeps up with live data.
let kernel = [1]; // the current kernel h
let current = 0; // the current slide position n
const convolveAt = (n) => {
const x = inputSeries.getNativeYValues();
let sum = 0;
// y[n] = sum of h[j] * x[n - j]: the kernel, flipped, over the input up to sample n
for (let j = 0; j < kernel.length && n - j >= 0; j++) sum += kernel[j] * x.get(n - j);
return sum;
};
// Two copies, so samples up to n are bright and those still to come are faint (NaN draws nothing)
const doneSeries = new XyCustomFilter(inputSeries, {
dataSeriesName: "Output y[n]",
filterFunction: (n) => (n <= current ? convolveAt(n) : NaN)
});
const toComeSeries = new XyCustomFilter(inputSeries, {
dataSeriesName: "Output still to come",
filterFunction: (n) => (n > current ? convolveAt(n) : NaN)
});
addStems("y", doneSeries, "#3BD16F");
addStems("y", toComeSeries, "#3BD16F", "44");
// A ring around the output sample being computed
const currentSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Current y[n]" });
sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(wasmContext, {
yAxisId: "y",
dataSeries: currentSeries,
pointMarker: new EllipsePointMarker(wasmContext, { width: 16, height: 16, fill: "#00000000", stroke: "#FFFFFF", strokeThickness: 2 })
})
);
const indices = (start, count) => Array.from({ length: count }, (_, i) => start + i);
const fmt = (v) => String(Math.round(v * 1000) / 1000);
const replace = (series, xs, ys) => {
series.clear();
if (xs.length) series.appendRange(xs, ys);
};
// Runs the convolution for the current settings and redraws everything. Returns the text for the results line.
function update(state) {
const x = state.input === "custom" ? parseNumbers(state.customX) : makeInput(state.input);
const kernelInfo = KERNELS.find((k) => k.key === state.kernel);
const h = state.kernel === "custom" ? parseNumbers(state.customH) : kernelInfo.make(state.width);
if (x.length === 0 || h.length === 0) {
return { maxPosition: 0, widthApplies: false, html: "Type some numbers, separated by commas." };
}
const N = x.length;
const M = h.length;
const length = N + M - 1;
const n = Math.min(state.position, length - 1);
kernel = h;
current = n;
// Replacing the input makes the two XyCustomFilters recompute the output
const padded = x.concat(new Array(M - 1).fill(0));
replace(inputSeries, indices(0, length), padded);
// The kernel, flipped and slid to n: h[n - k] sits at k = n - j for j = 0 … M - 1
replace(kernelSeries, indices(0, M).map((j) => n - j), h);
// Read the output back from the filters
const y = indices(0, length).map((i) => (i <= n ? doneSeries : toComeSeries).getNativeYValues().get(i));
replace(currentSeries, [n], [y[n]]);
xAxis.visibleRange = new NumberRange(-M - 0.5, length + 0.5);
const terms = productsAt(x, h, n).filter((t) => t.x !== 0 && t.h !== 0);
const working =
terms.length === 0
? "0 (no overlap)"
: terms.length <= 5
? terms.map((t) => `${fmt(t.x)}×${fmt(t.h)}`).join(" + ") + ` = <b>${fmt(y[n])}</b>`
: `the sum of ${terms.length} products = <b>${fmt(y[n])}</b>`;
const list = y.length <= 16 ? `<br>y = [${y.map(fmt).join(", ")}]` : "";
return {
maxPosition: length - 1,
widthApplies: !["difference", "custom"].includes(state.kernel),
html:
`y[${n}] = Σ x[k]·h[${n}−k] = ${working}` +
` · Length: N + M − 1 = ${N} + ${M} − 1 = <b>${length}</b>${list}`
};
}
controls.refresh();
// Hover for values, scroll to zoom, drag to pan, double-click to reset
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
}
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
FastImpulseRenderableSeries,
FastLineRenderableSeries,
XyDataSeries,
XyCustomFilter,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Sample" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Value" }));
const x = getYourSignal(); // e.g. sensor readings
const h = new Array(7).fill(1 / 7); // the kernel: a 7-sample moving average
// Pad the input with h.length - 1 zeros, so the output has all N + M - 1 samples
const padded = [...x, ...new Array(h.length - 1).fill(0)];
const input = new XyDataSeries(wasmContext, {
xValues: padded.map((_, i) => i),
yValues: padded,
dataSeriesName: "Input"
});
// The output: y[n] = sum of h[j] * x[n - j], computed by SciChart.js from the input series
const output = new XyCustomFilter(input, {
dataSeriesName: "Output",
filterFunction: (n: number) => {
const values = input.getNativeYValues();
let sum = 0;
for (let j = 0; j < h.length && n - j >= 0; j++) sum += h[j] * values.get(n - j);
return sum;
}
});
sciChartSurface.renderableSeries.add(
new FastImpulseRenderableSeries(wasmContext, { dataSeries: input, stroke: "#50C7E0", fill: "#50C7E0", size: 6 }),
new FastLineRenderableSeries(wasmContext, { dataSeries: output, stroke: "#3BD16F", strokeThickness: 3 })
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const ConvolutionChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
FastImpulseRenderableSeries,
FastLineRenderableSeries,
XyDataSeries,
XyCustomFilter,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
@Component({
selector: "app-convolution-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class ConvolutionChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Sample" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Value" }));
const x = getYourSignal(); // e.g. sensor readings
const h = new Array(7).fill(1 / 7); // the kernel: a 7-sample moving average
// Pad the input with h.length - 1 zeros, so the output has all N + M - 1 samples
const padded = [...x, ...new Array(h.length - 1).fill(0)];
const input = new XyDataSeries(wasmContext, {
xValues: padded.map((_, i) => i),
yValues: padded,
dataSeriesName: "Input"
});
// The output: y[n] = sum of h[j] * x[n - j], computed by SciChart.js from the input series
const output = new XyCustomFilter(input, {
dataSeriesName: "Output",
filterFunction: (n: number) => {
const values = input.getNativeYValues();
let sum = 0;
for (let j = 0; j < h.length && n - j >= 0; j++) sum += h[j] * values.get(n - j);
return sum;
}
});
sciChartSurface.renderableSeries.add(
new FastImpulseRenderableSeries(wasmContext, { dataSeries: input, stroke: "#50C7E0", fill: "#50C7E0", size: 6 }),
new FastLineRenderableSeries(wasmContext, { dataSeries: output, stroke: "#3BD16F", strokeThickness: 3 })
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
XyCustomFilteris a data series computed from another one. SciChart.js calls itsfilterFunction(index, y)for every sample when the filter is created, when the function is replaced or when the input is cleared and refilled, and only for the new samples when you append. A causal kernel only looks back, so appended data is filtered correctly without recomputing the rest.FastImpulseRenderableSeriesdraws stems, one line and dot per sample, the usual way to show discrete signals and kernels.LeftAlignedOuterVerticallyStackedAxisLayoutStrategystacks the y-axes into lanes, so the input, kernel and output share one x-axis and line up sample for sample.- Returning
NaNfrom a filter function leaves a gap, which is how the demo shows the output "still to come" in a fainter colour.
Apply a kernel to live data
The same filter smooths a stream as it arrives. Append to the raw series and the filtered line follows, with no extra code:
const { XyDataSeries, XyCustomFilter, FastLineRenderableSeries } = SciChart;
const rawData = new XyDataSeries(wasmContext, { dataSeriesName: "Raw" });
const kernel = [0.1, 0.2, 0.4, 0.2, 0.1]; // any kernel; this one sums to 1
// y[n] = sum of h[j] * x[n - j], over the samples received so far
const filtered = new XyCustomFilter(rawData, {
dataSeriesName: "Filtered",
filterFunction: (n) => {
const x = rawData.getNativeYValues();
let sum = 0;
for (let j = 0; j < kernel.length && n - j >= 0; j++) sum += kernel[j] * x.get(n - j);
return sum;
}
});
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, { dataSeries: rawData, stroke: "#50C7E066" }),
new FastLineRenderableSeries(wasmContext, { dataSeries: filtered, stroke: "#3BD16F", strokeThickness: 2 })
);
rawData.appendRange(xValues, yValues); // the filtered line follows automatically
Two cautions: updating one existing raw value refilters only that sample, so later samples that depend on it keep their old values (set the filterFunction again to recompute everything); and with a fifoCapacity series the index passed to the function counts samples in order, while getNativeYValues() holds the wrapped buffer, so keep your own copy of the recent samples instead.
Convolution without a chart library
If you only need the numbers, direct convolution is two loops. This returns the full output of N + M − 1 samples, and gives [0, 1, 2.5, 4, 1.5] for the worked example above:
// y[n] = sum over k of x[k] * h[n - k]
function convolve(x, h) {
const y = new Array(x.length + h.length - 1).fill(0);
for (let n = 0; n < y.length; n++) {
for (let k = Math.max(0, n - h.length + 1); k <= Math.min(n, x.length - 1); k++) {
y[n] += x[k] * h[n - k];
}
}
return y;
}
convolve([1, 2, 3], [0, 1, 0.5]); // [0, 1, 2.5, 4, 1.5]
See it in the demo app: JavaScript trendline and moving average filters · React trendline and moving average filters · Angular trendline and moving average filters, where the moving average is a convolution with a flat kernel. For live signal processing, see the JavaScript audio analyzer with FFT.
Go deeper: SciChart.js custom filter documentation, the built-in moving average filter, and the impulse (stem) series.
Frequently asked questions
What is convolution in simple terms?
Convolution is a sliding weighted sum. You take a short list of weights, called the kernel, and slide it along a signal. At each position you multiply the overlapping values and add them up, giving one output value. A kernel of equal weights gives a moving average; other kernels sharpen, delay, echo or detect edges.
What is the formula for convolution?
For sampled signals, y[n] = Σ x[k] h[n − k], summed over every k: the input x is multiplied by the kernel h, flipped and shifted by n, and the products are added. For continuous signals, the sum becomes an integral: (f ∗ g)(t) = ∫ f(τ) g(t − τ) dτ, taken over all τ.
What is the convolution theorem?
The convolution theorem says that convolving two signals in time is the same as multiplying their Fourier transforms in frequency. So you can convolve by taking the FFT of both signals, multiplying the results bin by bin and taking the inverse FFT. For long kernels, that takes far fewer operations than direct convolution.
What is the difference between convolution and cross-correlation?
Both slide one signal along another and sum the products. Convolution flips the kernel first; cross-correlation doesn't. Convolution answers what a system does to a signal; cross-correlation measures how similar two signals are at each shift, which is how you find a known pattern or a time delay. For a symmetric kernel the two give the same result.
What is convolution in a CNN?
A convolutional neural network slides small two-dimensional kernels, typically 3 by 3 pixels, across an image and sums the products at each position, which is the same operation in two dimensions. The network learns the kernel weights during training. Most deep learning libraries compute cross-correlation, without the flip, and still call it convolution.
How do I calculate a convolution in JavaScript?
Write two nested loops: for each output index n from 0 to N + M − 2, add up x[k] × h[n − k] for every k where both values exist. That is direct convolution, and it is fast enough for short kernels. For long kernels, use an FFT: zero-pad both arrays, transform them, multiply and transform back.
Sources
- Smith, S. W., The Scientist and Engineer's Guide to Digital Signal Processing: chapter 6, Convolution, chapter 7, Properties of Convolution and chapter 18, FFT Convolution, including the measured crossover between direct and FFT convolution.
- Smith, J. O., Mathematics of the Discrete Fourier Transform, Stanford CCRMA: Convolution and the Convolution Theorem.
- Oppenheim, A. V. and Schafer, R. W., Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, chapter 2 (linear time-invariant systems and the convolution sum) and chapter 8 (circular convolution and the DFT).
- Burnett-Thompson, A. (2007), A 3D Local Positioning System to track A Neutrally Buoyant Flow Follower, PhD thesis, University of Manchester, UK, chapter 3. The associated published paper is Burnett-Thompson, A. and York, T. (2007), A 3D Acoustic Local Positioning System to Track a Neutrally Buoyant Flow Follower, IEEE Instrumentation and Measurement Technology Conference (IMTC 2007). The direct-versus-FFT convolution diagram on this page is adapted from it.
- MIT OpenCourseWare, 6.003 Signals and Systems, Lecture 8: Convolution.
- PyTorch documentation, Conv2d, which defines its "convolution" layer as cross-correlation.