vec2word — Map embedding vectors to nearest vocabulary words.
vec2word(emb, M) returns the nearest vocabulary word for each row of M. [words, dist] = vec2word(emb, M, k) returns the k nearest words and distances.
Syntax
words = vec2word(emb, M)
[words, dist] = vec2word(emb, M, k, 'Distance', distance)Inputs
emb- Type
Any- Required
- Yes
- Description
- wordEmbedding object.
M- Type
NumericArray- Required
- Yes
- Description
- Embedding vectors, one vector per row.
k- Type
NumericScalar- Required
- No
- Default
1- Description
- Number of nearest words.
NameValue- Type
Any- Required
- Variadic
- Description
- Name-value options: Distance ('cosine' or 'euclidean').
Returns
words- Type
Any- Description
- Closest vocabulary words.
dist- Type
NumericArray- Description
- Distances to input vectors.
Returned values from vec2word depend on how many outputs the caller requests.
Errors
RunMat:vec2word:InvalidInput- When
- Inputs do not match a supported vec2word form.
- Message
vec2word received invalid input
RunMat:vec2word:TooManyOutputs- When
- The requested output count exceeds the canonical signatures.
- Message
vec2word: too many output arguments
Supported forms
words = vec2word(emb, M)
[words, dist] = vec2word(emb, M, k)
[words, dist] = vec2word(emb, M, k, 'Distance', distance)
words is a string array. dist is a numeric matrix.
distance must be "cosine" or "euclidean".
M columns must equal emb.Dimension.
Native integer M and native integer k require RunMat language extensions to be enabled.
Behavior
emb must be a RunMat wordEmbedding compatibility object.
M must be an n-by-emb.Dimension numeric matrix.
k is an optional positive integer from 1 through the vocabulary size. The default is 1.
Native integer storage for M and native integer storage for k are independent RunMat language extensions. Integer query values must be exactly representable as double before distance calculation, while k is decoded as an exact structural value.
The default distance metric is cosine distance. vec2word(___, 'Distance', 'euclidean') uses Euclidean distance.
words is an n-by-k string array. dist is an n-by-k numeric matrix.
For zero-norm query or vocabulary vectors under cosine distance, RunMat reports infinite distance so finite matches sort ahead of them.
Execution and residency
vec2word compares host-resident word embedding model data and has no provider kernel. Supported resident query data may gather automatically through its owning provider.
vec2word compares host text-model storage and has no provider kernel. Supported resident query data may gather automatically through its owning provider.
Implementation boundary
The current host implementation scores the vocabulary and sorts candidate distances for each query row; it is not an approximate-nearest-neighbor index. Returned words and distances are host-owned, and successful resident input gathering does not imply a provider search kernel.
Finite host allocation
The current implementation requires an Unbounded host allocation policy. Under Managed finite allocation, a shared family guard rejects before gather, model cloning, mutation or filesystem work because complete text-model scratch and metadata ownership is not yet implemented. Authority is checked again after suspension and before publication, and failures are terminal rather than permission to replay. This refusal is an implementation frontier, not completion of finite resource support.
Examples
Find Nearest Words
emb = readWordEmbedding('vectors.vec');
M = word2vec(emb, ["king" "queen"]);
words = vec2word(emb, M)Expected output:
`words` contains the nearest vocabulary word for each vector row.Return Multiple Neighbors
emb = readWordEmbedding("vectors.vec"); M = word2vec(emb, ["king" "queen"]);
[words, dist] = vec2word(emb, M, 3, "Distance", "cosine")Expected output:
`words` and `dist` have three columns.Using vec2word with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how vec2word changes the result.
Run a small vec2word example, explain the result, then change one input and compare the output.
FAQ
Which distances are supported?⌄
RunMat supports "cosine" and "euclidean".
Does vec2word execute on the GPU?⌄
No. It compares the host-resident embedding model.
Related Strings functions
Text Analytics
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 · 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
Related guides
Source you can read
Every RunMat function's source is public. Read exactly how vec2word is executed, line by line, in Rust.
- View the source for vec2word in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.