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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
documentsOrBagOrMatrix | Any | Yes | — | tokenizedDocument object, bag model, word vector, or numeric matrix. |
queriesOrMatrix | Any | Yes | — | Query tokenizedDocument object, word vector, or numeric matrix. |
Returns
| Name | Type | Description |
|---|---|---|
similarities | Any | Pairwise cosine-similarity matrix. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:cosineSimilarity:InvalidInput | Inputs do not match a supported cosineSimilarity form. | cosineSimilarity: invalid input |
RunMat:cosineSimilarity:DimensionMismatch | Matrix 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 ofMas a real sparse matrix.cosineSimilarity(M1, M2)returns anm1-by-m2sparse matrix comparing each row ofM1to each row ofM2; both matrices must have the same number of columns.cosineSimilarity(documents)accepts RunMattokenizedDocumentobjects 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 fromdocuments.cosineSimilarity(bag)andcosineSimilarity(bag, queries)accept RunMatbagOfWordsandbagOfNgramscompatibility objects and use their stored counts and terms.- Real numeric and text-model results are returned as RunMat
SparseTensorvalues. Zero-norm rows produce storedNaNsimilarities, 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
ComplexTensorcompatibility fallback rather than MATLAB's sparse complex matrix representation. gpuArrayinputs 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.
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
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.