encode — Encode documents as sparse word or n-gram count matrices.
encode(bag, documents) encodes tokenizedDocument input or a row word vector against a RunMat bagOfWords or bagOfNgrams compatibility object.
Syntax
counts = encode(bag, documentsOrWords, Name, Value, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
bag | Any | Yes | — | bagOfWords or bagOfNgrams model. |
documentsOrWords | Any | Yes | — | tokenizedDocument object or row word vector. |
NameValue | Any | Variadic | — | Name-value options: DocumentsIn, ForceCellOutput. |
Returns
| Name | Type | Description |
|---|---|---|
counts | Any | Sparse word or n-gram count matrix. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:encode:InvalidInput | Inputs do not match a supported Text Analytics encode form. | encode: invalid input |
How encode works
bagmust be a scalar RunMatbagOfWordsorbagOfNgramsobject.documentscan be a RunMattokenizedDocumentobject. A non-tokenized row word vector is accepted as one document.- The result is a RunMat sparse double matrix. By default, documents are rows and bag terms are columns.
encode(___, 'DocumentsIn', 'rows')returns one row per document. This is the default.encode(___, 'DocumentsIn', 'columns')returns one column per document.encode(___, 'ForceCellOutput', true)wraps the sparse result in a 1-by-1 cell array. This preserves the documented scalar-bag cell-output form without pretending object-array parity exists.- Words or n-grams not present in the bag model are ignored.
- For
bagOfNgrams, RunMat encodes the n-gram rows stored on the compatibility object and derives scan lengths from those rows. - Non-scalar bag object arrays and native MATLAB sparse model storage remain broader Text Analytics/runtime work.
GPU memory and residency
encode currently gathers provider inputs and returns host sparse output because RunMat sparse values are host-resident.
Examples
Encode Documents With A Bag Of Words
bag = bagOfWords(tokenizedDocument(["alpha beta"; "beta gamma"]));
newDocuments = tokenizedDocument(["beta beta delta"; "alpha gamma"]);
counts = encode(bag, newDocuments)Expected output:
`counts` is a sparse 2-by-3 matrix using `bag.Vocabulary` as the column order.Put Documents In Columns
counts = encode(bag, ["alpha" "beta" "alpha"], "DocumentsIn", "columns")Expected output:
`counts` is a sparse matrix with one column because the word vector is one document.Encode N-Grams
bag = bagOfNgrams(tokenizedDocument("a b a"), "NgramLengths", [1 2]);
counts = encode(bag, tokenizedDocument("a b a b"))Expected output:
`counts` contains unigram and bigram counts for n-grams stored in `bag.Ngrams`.Using encode with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how encode changes the result.
Run a small encode example, explain the result, then change one input and compare the output.
FAQ
Does encode return sparse output?⌄
Yes. RunMat returns a host SparseTensor count matrix for both bagOfWords and bagOfNgrams inputs.
Does ForceCellOutput implement bag object arrays?⌄
No. RunMat supports the scalar-bag cell wrapper form. MATLAB object-array identity and non-scalar bag arrays remain tracked by the Text Analytics umbrella issue.
Does encode execute on the GPU?⌄
No. It gathers provider inputs when needed, uses host text metadata, and returns host sparse values.
Related Strings functions
Text Analytics
addDependencyDetails · addEntityDetails · addLemmaDetails · addPartOfSpeechDetails · addSentenceDetails · addTypeDetails · bagOfNgrams · bagOfWords · cosineSimilarity · doc2sequence · 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 encode is executed, line by line, in Rust.
- View the source for encode 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.