Generated reference › KNN Search — Machine Learning/Classical Models
kind: generated#block#machine-learning-classical-models

KNN Search — Machine Learning/Classical Models

Machine_Learning/Classical_Models/KNN_Search · 1 input / 2 output port(s) at insert · exports to Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text

Description#

The block's own DESCRIPTION_HTML, rendered verbatim — the same text the config dialog's info panel and the library navigator show. Fix a wrong sentence in the block's .cpp (R-D9), never here.

KNN Search

Machine Learning / Classical Models

Finds the K training points nearest the input and reports which they are and how far away – MATLAB's knnsearch(X, u.', 'K', K, 'Distance', metric) with the training set pasted in as config:

di = dist(u, X(i,:)),   then the K smallest, nearest first.

It is not a classifier: KNN Classifier takes the same neighbours and votes on a class; this block hands over the neighbours themselves, for a caller that builds its own rule on top.

Ports

  • u – the query, a column [d,1] matching the d columns of Training Set.
  • idx – a column [K,1]: the training-set row of each neighbour, nearest first, counted from Index Base.
  • dist – a column [K,1]: the distance to each of those neighbours, in the same order, so it never decreases down the column.

Parameters

  • Training Set – the [N,d] matrix, one training point per row, which is knnsearch's X. N is at most 256.
  • Neighbors – K, a whole number from 1 to N.
  • Distance – the metric:
    • Euclidean – the square root of the summed squared differences. The default, as in knnsearch.
    • City block – the summed absolute differences.
    • Chebyshev – the largest absolute difference.
  • Index Base – what the first training row is called:
    • One-based (MATLAB) – the first row is 1, as knnsearch reports it. The default.
    • Zero-based (PyTorch, numpy) – the first row is 0.
  • Sampling Time (s) – zero or less inherits the solver's rate; a positive value runs the block at that period.

Code export

All ten targets: Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog and PLC Structured Text, all from one program, so every target does the same arithmetic in the same order as the simulation. The training set, K, the metric and the base are baked in at export time.

The three HDL targets carry the search in real arithmetic and quantize only at the ports: simulation-only, not offered as synthesizable. (KNN Classifier is the synthesizable one: its answer is a class, which needs no square root and no distance at the port.)

Simulink bridge

None (Support::None). The Statistics and Machine Learning Toolbox block statsClustering/KNN Search takes a fitted searcher object as its parameter rather than numbers, which no parameter rule can carry across. The bridge reports this block rather than dropping it silently, and it has no parity testbench; code export verification covers all ten languages.

Notes

  • Verified against R2026a knnsearch for all three metrics: see the source banner for the data and the measured agreement.
  • Ties go to the lower training row, which is knnsearch's own order, measured with both its kd-tree and exhaustive searchers. It is decided by counting rather than sorting, so every target agrees on exactly which points tie.
  • The Euclidean ranking is taken on the squared distance and only the published value is rooted, so a root that rounds two different distances together cannot create a tie the data does not have.
  • Cost is O(N²) comparisons per sample – inherent to ranking without storing a sorted order, and fine for the small baked sets this block targets.
  • At a near-tie in distance the HDL targets can rank differently. They receive the query quantized to Q16.16 at the port, one quantum of which is about 1.5e-5, where the in-app run uses doubles – so two training points whose distances differ by less than that can swap places, and idx then differs by a whole row. It is the same caveat KNN Classifier carries.
  • Algebraic and stateless, and nonlinear: it carries no state space.

Code facts#

FactValue
registered typeMachine_Learning/Classical_Models/KNN_Search
familyMachine_Learning/Classical_Models
solver environment classICoreBlock_0_Machine_Learning_1_Classical_Models_2_KNN_Search
sourcesrc/ICoreBlocks/ICoreBlockLibrary/Blocks/Machine_Learning/Classical_Models/KNN_Search/ICoreBlock_0_Machine_Learning_1_Classical_Models_2_KNN_Search.cpp
headersrc/ICoreBlocks/ICoreBlockLibrary/Blocks/Machine_Learning/Classical_Models/KNN_Search/ICoreBlock_0_Machine_Learning_1_Classical_Models_2_KNN_Search.h
default size on canvas140 × 80 px
ports at insert1 in, 2 out
code generators implementedPython, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text

Ports#

#DirectionSignal typeDescription label
1inICoreDoubleu
2outICoreDoubleidx
3outICoreDoubledist

Ports the constructor creates. A block whose port list changes with its configuration adds or removes ports at load time; the count above is the one a freshly inserted block has.

Configuration variables#

Config variableDefaultSimulink parameter
Training Set[0 0; 0.2 0.1; 1 1; 1.2 0.9; -1 0.5; -0.8 0.7]—
Neighbors3—
DistanceEuclidean%~%City block%~%Chebyshev~~Euclidean—
Index BaseOne-based (MATLAB)%~%Zero-based (PyTorch, numpy)~~One-bas…—

Every block also carries Sampling Time (s) from ICoreBlockSolverEnvironment: zero or less inherits the solver's rate, a positive value runs the block at that period.

supportSupport::None
Simulink path—
port-count rulePortsParam::None
SampleTime parameteryes

Caveat (shown to the user): the Statistics and Machine Learning Toolbox block statsClustering/KNN Search takes a fitted SEARCHER OBJECT as its parameter rather than numbers, which no ParamRule can carry across; the block is reported rather than dropped when a model crosses

Catalog contract: src/ICoreBlocks/ICoreCoder/ICoreCommandSystem/SimulinkBridge/ICoreSimulinkBlockCatalog.h

Description vs code#

The checker has a blind spot here — it could not resolve something (a grouped port bullet, a computed config name), which is reported and never counted as a pass. A reader has to settle it:

  • B0 no sample under docs/generated/samples/ — nothing to cross-check (P8.1)

The verdict above is tools/docs/check_block_descriptions.py (P7.1), which compares LISTS. It cannot read a sentence: "stateless" on a block with a state, an initial-value semantic the recursion does not implement, a "not synthesizable" caveat the HDL banner contradicts. That is the agent audit (P7.3) on BLOCK_DESCRIPTION_AUDIT.md, and this tool's green is not a substitute for one.

File banner (developer view)#

The top comment of the block's .cpp — the maths, the realization and the export strategy, addressed to whoever changes it. It must not contradict the description above (P7.5).

KNN Search -- the K nearest training points and their distances (MATLAB's knnsearch) s_i = sum_j (u_j - X[i][j])^2 Euclidean (published as sqrt(s_i)) = sum_j |u_j - X[i][j]| city block = max_j |u_j - X[i][j]| Chebyshev rank_i = #{ j : s_j < s_i } + #{ j < i : s_j == s_i } idx(rank_i), dist(rank_i) = i + base, the published distance for rank_i < K

Rank by counting is KNN Classifier's selection, and it IS "order by (distance, index)": knnsearch's own tie rule, measured on R2026a with both its kd-tree and exhaustive searchers. Ranking the SQUARED Euclidean distance and rooting only what is published means no rounding of a root can merge two distances the data keeps apart.

Measured against R2026a, twice:

  • the search, transcribed, against knnsearch(X, Q, 'K', 4, 'Distance', m) for all three

metrics on X = [0 0; 1 0; 0 1; -1 0; 2.5 1.5; -0.7 -1.9; 1.3 -0.4; 0.2 2.2] and six queries holding three-way ties at 0 and at [0.5 0.5] and a two-way tie at [3 -2]: indices identical, distances bit for bit;

  • the EXPORTED Python cores of the three export-verify rigs, over 41 queries along the rig's

line, against knnsearch on the same set: indices identical, distances within 4.9e-15.

Written once as an ICoreStatementProgram, so all ten exports do the run's arithmetic in the run's order; the three HDL targets therefore carry it in real (simulation-only).

Sample results#

No sample run is committed for this block. Samples come from the headless harness (DOCS_PLAN.md P8.1) into docs/generated/samples/; until one exists this block's behaviour is witnessed by the parity and export-verification suites, not by a plot here.