Working with Text Data in MATLAB
Learn how to efficiently manipulate string arrays, apply regular expressions, and extract insights from raw textual data to elevate your programming workflows.
Start LessonUnderstanding Character Arrays in MATLAB
When you begin processing text data in MATLAB, the most fundamental data structure you will encounter is the character array. Defined by enclosing text in single quotation marks (for example, 'MATLABTECH'), a character array is traditionally how early versions of MATLAB handled all text. But what is it exactly underneath the surface? In MATLAB, a character array is strictly a 1-by-N row vector of individual letters. This means that if you declare a variable containing a 10-letter word, MATLAB dynamically allocates memory for an array with exactly 10 distinct elements.
Because it operates as a standard mathematical vector, each character is stored sequentially using 16-bit UTF-16 encoding. The primary advantage of this structure is that it allows for extremely granular, low-level manipulation. You can loop through a character array exactly as you would an array of numbers, making it excellent for algorithms that require character-by-character analysis or when interfacing with lower-level languages like C/C++ via MEX files. Furthermore, because it is the legacy format, thousands of older MATLAB toolboxes and functions strictly expect character arrays as input.
However, this vector-based nature introduces significant complexity when you need to store multiple pieces of text. Because all rows in a standard MATLAB matrix must have the exact same number of columns, you cannot easily stack a 5-letter word on top of a 10-letter word without manually padding the shorter word with five blank spaces. Historically, developers bypassed this by wrapping character arrays inside of cell arrays (e.g., {'Word1', 'LongerWord2'}), which added overhead. Understanding the 1-by-N nature of character arrays is essential for debugging legacy code and preparing data for modern analysis.
The Modern String Data Type
To resolve the inherent limitations and rigid dimensional rules of character arrays, MATLAB introduced the modern string data type, accessible by enclosing text in double quotation marks (e.g., "MATLABTECH"). This shift represents one of the most significant architectural upgrades to text processing in MATLAB, drastically simplifying code readability, memory management, and advanced data analytics workflows. If you are developing new applications, particularly in R2018b or later, strings should be your default choice for text representation.
Unlike a character array—which behaves as a vector of individual letters—a piece of text enclosed in double quotes is treated by MATLAB as a 1-by-1 scalar object. Regardless of whether the string contains a single word, an entire paragraph, or a massive block of log data, its dimensions remain 1-by-1. This is a game-changer for data organization. Because a string is a scalar container, you can instantly create standard N-dimensional matrices of text without ever worrying about padding varying word lengths with trailing spaces. It allows text to behave identically to numeric arrays in tables and structures.
Beyond structural convenience, the string data type unlocks a highly optimized suite of text manipulation functions. Comparing two strings no longer requires verbose functions like strcmp; you can seamlessly use standard logical operators like == and ~=. Furthermore, strings interact flawlessly with missing data paradigms; you can assign the <missing> value to a string array just as you would use NaN in a numeric array. This makes the string data type the ultimate tool for machine learning preprocessing, data wrangling, and building scalable engineering applications.
Extracting Text from External Files
Engineering and data science workflows rarely rely on hardcoded text; the real power of MATLAB lies in its ability to ingest, parse, and analyze massive external datasets. Whether you are dealing with output logs from a PID controller, CSV files containing sensor telemetry, or unstructured text documents, you must know how to properly read file contents into the MATLAB workspace. The method you choose significantly impacts both the performance of your script and how easily you can manipulate the resulting data.
For raw, unstructured text files, the fileread function is incredibly efficient. When executed, fileread opens the target file, reads its entire contents, and returns it as a single, contiguous character array. However, processing a massive block of unseparated text is difficult. To make the data actionable, modern MATLAB workflows immediately wrap the output of fileread into the string() function, converting it into a scalar string. From there, applying the splitlines function is the standard best practice. splitlines automatically detects newline characters (regardless of whether they are Windows or UNIX style) and fractures the massive text block into a highly organized N-by-1 string array, where each element corresponds directly to a single line in the original file.
Alternatively, if you are reading highly structured tabular data, functions like readtable or textscan offer advanced extraction by allowing you to define specific delimiters (like commas or tabs) and data types upon import. By mastering these file I/O operations, you ensure your MATLAB programs can act as dynamic, automated analysis engines capable of handling real-world data pipelines effortlessly.
Slicing and Subset Extraction
Slicing is the technical term for extracting a specific subset of characters from a larger body of text. Depending on whether you are working with legacy character arrays or modern string arrays, your approach to slicing in MATLAB will be fundamentally different. Understanding both methodologies is critical, as you will frequently encounter scenarios where you must clean dirty data, strip file extensions, or extract specific substrings based on logical patterns.
When working with a character array (single quotes), slicing relies on standard matrix indexing. Because 'Engineering' is a 1-by-11 vector, extracting the first six letters is as simple as calling text(1:6), which returns 'Engine'. You can also use logical indexing or step values, such as text(1:2:end) to extract every other letter. However, this method completely fails when applied to the modern string data type. Because a string is a 1-by-1 scalar container, calling str(1:6) on the string "Engineering" will throw an error, as the array does not have 6 elements to index into.
To slice strings, MATLAB provides a dedicated suite of highly semantic functions: extractBefore, extractAfter, and extractBetween. These functions are incredibly powerful because they operate based on patterns rather than rigid numerical indices. For example, you can extract everything between two specific words or symbols without needing to manually count character positions. If you require advanced pattern matching, MATLAB’s regexp (regular expressions) engine integrates perfectly with string arrays, allowing you to slice text based on complex algorithmic rules—such as extracting only the numerical values hidden within a block of alphanumeric telemetry data.
Vertical Concatenation of Text
Vertical concatenation is the computational process of stacking multiple pieces of text on top of one another to form a column vector. In MATLAB, concatenation is typically driven by the square bracket operator, where a semicolon ; dictates a new row (e.g., [row1; row2]). While the syntax remains consistent, the behavior and execution of vertical concatenation differ wildly depending on whether you are manipulating character arrays or strings—often leading to frustrating errors for beginners.
If you attempt to vertically concatenate two character arrays of different lengths using standard brackets—for example, ['Car'; 'Vehicle']—MATLAB will immediately throw a dimensional mismatch error. Because character arrays are matrices of letters, the matrix rules enforce that every row must have the exact same number of columns. To bypass this, developers traditionally had to use the char() function or strvcat, which forcibly appended hidden spaces to the shorter words so the matrix edges aligned. This whitespace padding often corrupted downstream logical comparisons, requiring constant trimming.
The modern string data type gracefully eliminates this entire problem. Because every string acts as an independent 1-by-1 container, strings do not care about the character lengths of their neighbors. You can effortlessly execute ["Car"; "Vehicle"] and MATLAB will instantly generate a clean 2-by-1 string array, totally devoid of padding. This structural freedom makes vertical concatenation of strings the absolute standard for dynamically building reports, assembling UI list boxes, or preparing multi-line output messages without the headache of matrix dimension management.
Horizontal Concatenation of Text
Horizontal concatenation is the process of merging multiple text elements side-by-side to form a single, continuous string of text. This operation is ubiquitous in programming—you use it to dynamically construct absolute file paths, generate custom command-line prompts, or merge numerical variables into readable text outputs for reporting. In MATLAB, you can achieve this via square brackets with a comma separator [text1, text2], the dedicated strcat function, or, most elegantly, the mathematical addition operator + when using strings.
Whitespace management is the most critical factor to consider when choosing your horizontal concatenation method. If you utilize the strcat function on legacy character arrays, MATLAB will automatically strip all trailing whitespace from the inputs before merging them. While helpful when cleaning data, this feature can destroy intentionally placed spaces (e.g., trying to combine 'Hello ' and 'World' using strcat yields 'HelloWorld'). To preserve whitespace in character arrays, you are forced to use the square bracket method.
By upgrading your workflow to use the modern string data type, horizontal concatenation becomes vastly more intuitive. The addition operator + is fully supported for strings, allowing you to write highly readable code such as "Status: " + statusVariable. The addition operator inherently respects and preserves all whitespace perfectly. Furthermore, if you are attempting to concatenate text with numerical values, leveraging modern formatting functions like compose or sprintf ensures your numerical precision is maintained while seamlessly blending the data into the final horizontal text output.