cosineSimilarity — Compute cosine similarity between documents, bag models, or numeric matrix rows.

cosineSimilarity compares rows of numeric matrices directly, or compares tokenizedDocument, bagOfWords, and bagOfNgrams inputs using tf-idf weighting derived from the first document or bag input.

Syntax

similarities = cosineSimilarity(documents)
similarities = cosineSimilarity(documents, queries)
similarities = cosineSimilarity(bag)
similarities = cosineSimilarity(bag, queries)
similarities = cosineSimilarity(M)
similarities = cosineSimilarity(M1, M2)

Inputs

NameTypeRequiredDefaultDescription
documentsOrBagOrMatrixAnyYestokenizedDocument object, bag model, word vector, or numeric matrix.
queriesOrMatrixAnyYesQuery tokenizedDocument object, word vector, or numeric matrix.

Returns

NameTypeDescription
similaritiesAnyPairwise cosine-similarity matrix.

Errors

IdentifierWhenMessage
RunMat:cosineSimilarity:InvalidInputInputs do not match a supported cosineSimilarity form.cosineSimilarity: invalid input
RunMat:cosineSimilarity:DimensionMismatchMatrix inputs have different numbers of columns.cosineSimilarity: matrix dimensions are not compatible

How cosineSimilarity works

  • cosineSimilarity(M) returns pairwise row cosine similarities for the rows of M as a real sparse matrix.
  • cosineSimilarity(M1, M2) returns an m1-by-m2 sparse matrix comparing each row of M1 to each row of M2; both matrices must have the same number of columns.
  • cosineSimilarity(documents) accepts RunMat tokenizedDocument objects and raw row word vectors; non-tokenized arrays must be row vectors representing one document.
  • cosineSimilarity(documents, queries) encodes query documents using the vocabulary and inverse-document-frequency weights derived from documents.
  • cosineSimilarity(bag) and cosineSimilarity(bag, queries) accept RunMat bagOfWords and bagOfNgrams compatibility objects and use their stored counts and terms.
  • Real numeric and text-model results are returned as RunMat SparseTensor values. Zero-norm rows produce stored NaN similarities, matching the mathematical undefined cosine case.
  • Complex matrix inputs use the Hermitian inner product. RunMat does not yet have a complex sparse value type, so complex results are returned as a dense ComplexTensor compatibility fallback rather than MATLAB's sparse complex matrix representation.
  • gpuArray inputs are gathered before evaluation because RunMat sparse output is currently host-resident and provider-resident sparse similarity kernels are tracked by the GPU fast-path audit.

GPU memory and residency

cosineSimilarity currently gathers provider inputs and returns host sparse output because RunMat sparse values are host-resident.

Examples

Compare Numeric Rows

S = cosineSimilarity([1 0; 1 1])

Expected output:

`S` is a sparse 2-by-2 matrix of row cosine similarities.

Compare Documents Against Queries

documents = tokenizedDocument(["alpha beta"; "beta gamma"]);
queries = tokenizedDocument("alpha");
S = cosineSimilarity(documents, queries)

Expected output:

`S` contains the similarity between each document and the query document.

Compare A Bag Model

bag = bagOfWords(tokenizedDocument(["alpha beta"; "beta gamma"]));
S = cosineSimilarity(bag)

Expected output:

`S` compares the bag rows using tf-idf weights derived from the bag counts.

Using cosineSimilarity with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how cosineSimilarity changes the result.

Run a small cosineSimilarity example, explain the result, then change one input and compare the output.

FAQ

Does cosineSimilarity return a sparse matrix?

Yes for real numeric, document, and bag inputs. Complex numeric inputs currently return a dense complex matrix because RunMat does not yet expose complex sparse storage.

Can query documents contain words not in the first input?

Yes. Query words or n-grams outside the first input's vocabulary are ignored, matching the fixed-vocabulary comparison model.

Does cosineSimilarity execute on the GPU?

No. The current implementation returns host sparse values. Provider-resident sparse output and GPU cosine kernels belong to the queued GPU fast-path audit.

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how cosineSimilarity is executed, line by line, in Rust.

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.

  • RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
  • Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.