RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

LicensePrivacy
/
See all docs
Builtin Reference
    • addDependencyDetails
    • addEntityDetails
    • addLemmaDetails
    • addPartOfSpeechDetails
    • addSentenceDetails
    • addTypeDetails
    • bagOfNgrams
    • bagOfWords
    • cosineSimilarity
    • doc2sequence
    • encode
    • extractFileText
    • extractHTMLText
    • fastTextWordEmbedding
    • findElement
    • getAttribute
    • htmlTree
    • ind2word
    • isVocabularyWord
    • normalizeWords
    • readWordEmbedding
    • removeLongWords
    • removeShortWords
    • removeStopWords
    • removeWords
    • stopWords
    • tokenDetails
    • tokenizedDocument
    • trainWordEmbedding
    • vaderSentimentScores
    • vec2word
    • word2ind
    • word2vec
    • wordEncoding
    • writeWordEmbedding

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. MATLAB documents double numeric matrices; RunMat mode separately gates single, logical, typed-integer, and resident matrix extensions.

Syntax

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

Inputs

NameTypeRequiredDefaultDescription
documentsOrBagOrMatrixAnyYes—tokenizedDocument object, bag model, word vector, or numeric matrix.
queriesOrMatrixAnyYes—Query 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.
  • All eight real or typed-complex integer classes are a RunMat-only extension and require each component to be exactly representable at the binary64 norm and inner-product boundary; aligned values above flintmax are accepted when their significant bits fit binary64.
  • Single, logical, and provider-resident numeric matrices are independent RunMat-only extensions.
  • 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. The public MATLAB reference does not specify zero-norm behavior; RunMat returns stored NaN similarities because the cosine quotient is mathematically undefined when either norm is zero.
  • 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.
  • Sparse-complex output, table adapters, and tall or distributed execution remain explicit general representation/container gaps rather than integer-storage gaps.

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.

Related Strings functions

Text Analytics

addDependencyDetails · addEntityDetails · addLemmaDetails · addPartOfSpeechDetails · addSentenceDetails · addTypeDetails · bagOfNgrams · bagOfWords · doc2sequence · encode · extractFileText · extractHTMLText · fastTextWordEmbedding · findElement · getAttribute · htmlTree · ind2word · isVocabularyWord · normalizeWords · readWordEmbedding · removeLongWords · removeShortWords · removeStopWords · removeWords · stopWords · tokenDetails · tokenizedDocument · trainWordEmbedding · vaderSentimentScores · vec2word · word2ind · word2vec · wordEncoding · writeWordEmbedding

Transform

append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · extractBetween · insertAfter · insertBefore · join · lower · pad · replace · replaceBetween · reverse · split · splitlines · strcat · strip · strjoin · strjust · strrep · strsplit · strtrim · upper

Core

blanks · char · compose · convertCharsToStrings · convertContainedStringsToChars · convertStringsToChars · genvarname · int2str · isletter · isspace · isStringScalar · isstrprop · mat2str · native2unicode · newline · num2str · sprintf · sscanf · str2double · str2num · strcmp · strcmpi · string · string.empty · strings · strlength · strncmp · strncmpi · strtok · unicode2native

Search

contains · endsWith · matches · startsWith · strfind

Pattern

digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern

Regex

regexp · regexpi · regexprep

Open-source implementation

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

  • View the source for cosineSimilarity in Rust on GitHub
  • Learn how the RunMat runtime works
  • Found a bug? Open an issue with a minimal reproduction.

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.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How cosineSimilarity works
  • GPU memory and residency
  • Examples
  • Compare Numeric Rows
  • Compare Documents Against Queries
  • Compare A Bag Model
  • Using cosineSimilarity with coding agents
  • FAQ
  • Related Strings functions
  • Text Analytics
  • Transform
  • Core
  • Search
  • Pattern
  • Regex
  • Open-source implementation
  • About RunMat