To split a MATLAB character vector at a delimiter, use strsplit: for example, parts = strsplit('red,green,blue', ','); returns a cell array containing three character vectors. For newer string-based code, convert the input with string and use split, which returns a string array.
What MATLAB means by a character array
MATLAB distinguishes character arrays from string arrays. A character vector is a one-row character array, commonly written with single quotes, such as 'red,green,blue'. A string scalar is written with double quotes, such as "red,green,blue". The two types can represent similar text, but MATLAB functions may return different container types for them.
A character array can also have multiple rows. This is often called a character matrix: every row has the same number of columns, so shorter lines are padded with spaces. That fixed-width layout matters when splitting text because a whole matrix is not always equivalent to one long character vector. If each row represents an independent record, split each row separately rather than joining the rows and accidentally making one record from several.
For many existing MATLAB scripts, strsplit is the direct answer to “split character array.” It is designed to divide text into pieces around a delimiter. The related split function is convenient when the data is already stored as strings. Choosing between them mainly depends on the input type and whether your later code expects cells or strings.
Split a character vector with strsplit
Pass a character vector and a delimiter to strsplit. The delimiter is removed from the output, and the pieces are returned in a cell array. Use curly braces to extract an individual character vector from that cell array.
text = 'name,age,city';
parts = strsplit(text, ',');
% parts is {'name', 'age', 'city'}
firstPart = parts{1};
Here, parts is a 1-by-3 cell array, while parts{1} is the character vector 'name'. This distinction is important: parentheses such as parts(1) return a cell, whereas curly braces return its contents. If a later function expects a cell array of text, keep the cell array; if it expects one token, extract that token with braces.
You can split on a different delimiter just by changing the second input. A tab-delimited line, for example, can be split with strsplit(text, sprintf('\t')). When there is no explicit delimiter, strsplit(text) splits at whitespace. For predictable code, specifying the delimiter is usually clearer than relying on the default.
Use split with string data
The split function is the string-oriented alternative. Convert a character vector explicitly with string when you want its output as a string array:
text = 'red,green,blue';
parts = split(string(text), ",");
% parts is a string array: ["red"; "green"; "blue"]
Unlike the cell-array result from strsplit, this result is a string array. In this example, it is a column of strings. Use parts(1) to select a string array element; use parts(1) or convert the selected value if your code has requirements for a particular text type. Do not assume that split and strsplit return interchangeable outputs just because both divide text.
String arrays can be useful when working with modern MATLAB functions that accept strings and when the input contains multiple text values. If a project or function specifically requires character vectors, strsplit may fit more naturally. When working across MATLAB releases, check the documentation for the version in use, especially if you are adopting newer string features in older code.
Choose the delimiter and handle repeated separators
A delimiter can be a comma, colon, tab, or other text. To split on more than one delimiter, provide a cell array of delimiter values to strsplit. For instance, a line that uses either commas or semicolons can be handled as follows:
text = 'red,green;blue';
parts = strsplit(text, {',', ';'});
Decide what repeated delimiters mean in your data. In a comma-separated list, 'a,,b' may indicate an intentionally empty middle field, or it may be accidental extra punctuation. strsplit supports the CollapseDelimiters option. Set it to false when adjacent delimiters must be treated separately so that empty fields can be represented:
parts = strsplit('a,,b', ',', 'CollapseDelimiters', false);
This option is useful when the position of fields matters. For example, if a missing middle value must not shift the meaning of later fields, collapsing separators could hide that missing field. Always test leading, trailing, and repeated delimiters with a short sample from the actual data; those cases often expose assumptions that a clean example does not.
Split a multirow character array row by row
For a character matrix with one record per row, convert its rows to a cell array of character vectors with cellstr, then split each row. The following pattern keeps each record’s tokens grouped separately:
A = ['red,green '; 'blue,black'];
rows = cellstr(A);
partsByRow = cell(size(rows));
for k = 1:numel(rows)
partsByRow{k} = strsplit(rows{k}, ',');
end
In this example, partsByRow{1} contains the pieces from the first row, and partsByRow{2} contains those from the second. The outer cell array holds one result per input row; each of those results is itself a cell array. This nested structure is useful when rows have different numbers of fields, because a regular numeric or character matrix cannot directly hold rows of different lengths without padding.
cellstr removes trailing spaces used to pad rows of a character matrix. That is usually appropriate when the spaces are just matrix padding. If trailing spaces are meaningful data, preserve and process the rows deliberately instead of assuming they are disposable. Also, do not use a character matrix merely because the input happens to be displayed in rows: first decide whether each row is a separate record or whether the matrix is a fixed-width representation of one dataset.
Convert the pieces for later calculations
Splitting creates text, not numbers. If the fields contain numeric values, convert them after splitting and check for failed conversions. For example:
text = '12,7.5,0';
parts = strsplit(text, ',');
values = str2double(parts);
Here, values is the numeric row vector [12 7.5 0]. A field that is not a valid number converts to NaN, so inspect the result with isnan if invalid or missing data needs to be detected. Avoid using str2num for ordinary text-to-number conversion; str2double is the appropriate choice for converting numeric text and does not evaluate the text as MATLAB code.
If the pieces contain dates, units, quoted fields, or other structured content, splitting alone may not be sufficient. A simple delimiter split does not understand every file format’s rules. For example, a comma inside a quoted CSV field is not necessarily a field boundary. Use a CSV-aware import function such as readtable for CSV files rather than trying to recreate the file parser with a basic split.
Common errors and practical checks
Many problems come from a mismatch between the input type, output type, and expected delimiter. Before adding more code, inspect the size and class of the value with size(text) and class(text). That can reveal whether you have a one-row character vector, a multirow character matrix, a string scalar, or a string array.
- Brace indexing error:
strsplitreturns a cell array, so useparts{1}for the text inside a cell. Useparts(1)when you want the cell itself. - Unexpected number of pieces: Confirm that the delimiter in the data is exactly the one supplied. A space, tab, comma, and semicolon are distinct characters.
- Missing fields disappear: Consider
'CollapseDelimiters', falsewithstrsplitwhen consecutive separators represent empty fields. - Rows are mixed together: Convert a character matrix to rows with
cellstrand process each row separately when rows are independent records. - Numbers remain text: Split first, then use
str2doubleand check forNaNvalues.
For debugging, print the original text and the result for a small representative input. Include edge cases such as an empty field or a delimiter at the beginning or end. This is faster than diagnosing a large downstream calculation whose inputs were split incorrectly.
When another MATLAB function is a better fit
Use strsplit when the task is straightforward division of a character vector around known delimiter text. Use split when the text is represented as strings and a string-array result suits the rest of the program. These functions are not full parsers, and they should not be treated as interchangeable with tools built for structured files.
For patterns more complex than fixed delimiters, regexp can identify matches using regular expressions, though its syntax and behavior require more care. For formatted text files, textscan can read data according to specified formats. For CSV and similar tabular files, readtable is often a better starting point because it is designed for importing structured columns. Choosing the right tool avoids special-case code for quoting, missing values, and data types.
Frequently Asked Questions
Does strsplit return a cell array or a string array?strsplit returns a cell array of character vectors for a character-vector input. The string-oriented split function returns strings when given string input. Check the output type before indexing or passing results to another function.
How do I split a character array at spaces?
Use strsplit(text) for the default whitespace split, or specify a space delimiter with strsplit(text, ' ') when only ordinary spaces should separate fields. The explicit version does not express the same intent as splitting on all whitespace characters.
How do I split every row in a char matrix?
Convert the matrix to row character vectors with rows = cellstr(A), then call strsplit on each element in a loop. This preserves the fact that each row is a separate record and allows rows to produce different numbers of tokens.
How can I keep empty fields between consecutive delimiters?
With strsplit, set 'CollapseDelimiters' to false. Test the behavior with the exact input pattern, including leading and trailing delimiters, because empty fields may be meaningful in your data format.
Can I split a CSV line with strsplit?
Only when you know the line follows a simple delimiter pattern with no CSV quoting complications. A comma inside a quoted field can be part of that field rather than a separator, so use readtable or another CSV-aware import method for general CSV files.
Related
- Line of Balance Spreadsheet: Build and Track Projects
- Balance of Payments Diagram: Structure and Examples
- Can You Play Split Fiction on Mac?
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Change Date Format in Excel Cells: A Step-by-Step GuideTo change how a date appears in an Excel cell, select the cell or range, press Ctrl+1 on…
- Excel Solver: How to Add Constraints and Set LimitsTo add constraints in Excel Solver, open Data > Solver, enter your objective and changing cells, then select…
- Capitalize in Excel: Shortcut Keys and Quick MethodsExcel has no built-in shortcut that changes selected text from lowercase to uppercase. To capitalize a column, enter…
- Excel Highlight Keyboard Shortcut: What Actually WorksIn Excel for Microsoft 365 on Windows, select the cell or range and press Alt+H, H to open…
- How to Sum a Row in Google Sheets: Simple FormulaTo sum a row in Google Sheets, put the total in an empty cell and enter =SUM(B2:F2). This…
- Excel Text to Columns: How to Make Results VerticalExcel’s Text to Columns feature splits text across columns, not down rows. To make the split results vertical,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.