Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 45 ยท Data Types and Text

Strings and Character Arrays

Learn text in MATLAB and Octave: char arrays versus string objects, joining, num2str, str2double, sprintf, strsplit, strrep and regexp, with Python stand-ins.

In MATLAB and Octave, text is just another kind of array. The classic text type is the character array, written with single quotes: 'hello' is a 1-by-5 row of characters, one per column. Everything you learned about matrices and indexing applies to it, which is powerful and occasionally surprising.

Newer MATLAB versions also have a second type, the string object, written with double quotes. Octave has no such object: in Octave, double quotes make an ordinary character array that also understands escape sequences. This lesson teaches the character-array world first because it works everywhere, then shows what the string type changes.

The code blocks marked matlab are read-only because MATLAB and Octave are not installed on this site. The runnable examples are Python stand-ins that reproduce the same operations, and each one says which MATLAB functions it mirrors.

Two kinds of text

Char array Single quotes. Works in MATLAB and Octave.
String object Double quotes. MATLAB only.

Check which one a variable holds with class(x).

1 / 2

Character arrays

A character array is created with single quotes. Because it is a matrix, you can ask for its size, index into it, reverse it and compare it:

MATLAB
name = 'Ada';
size(name)        % 1 3
name(1)           % 'A'
name(end:-1:1)    % 'adA'
class(name)       % 'char'
double(name)      % 65 100 97

Each character is stored as a number (its character code), and double shows it. Arithmetic on text therefore gives numbers: 'a' + 1 is 98, and char('a' + 1) is 'b'. This is how you build simple ciphers or convert case by hand.

To make a real two-dimensional block of text, every row must have the same number of columns. ['cat'; 'horse'] is an error because 3 does not equal 5. Pad the shorter row (char('cat', 'horse') does it for you) or, better, store the words in a cell array.

Python Characters are numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The shifted text shows how little separates a letter from its neighbour: Ada becomes Beb. In MATLAB you would write char(double(name) + 1); Python needs the explicit loop because its strings are not arrays.

Strings versus char arrays in MATLAB

In MATLAB (since R2016b), double quotes create a string array. A string is one item in an array, not a row of characters, so "hello" has size 1-by-1 and its length is measured with strlength:

MATLAB
s = "hello";
size(s)           % 1 1       (one string)
strlength(s)      % 5
c = 'hello';
size(c)           % 1 5       (five characters)
class(s)          % 'string'

Strings give you friendlier tools: + joins them ("a" + "b" is "ab"), == compares them ("cat" == "cat" is 1), and an array like ["red" "green" "blue"] holds words of different lengths with no padding. Missing text is represented by <missing>.

Octave treats "hello" as a plain char array, so code that relies on + joining or strlength fails there. If your code must run in both, stay with single quotes and the functions below, which exist in both.

Task Char array (both) String (MATLAB only)
Create 'text' "text"
Length numel(s) strlength(s)
Join [a b], strcat(a, b) a + b
Compare strcmp(a, b) a == b
Convert string(c) / char(s)

Joining text

Square brackets concatenate char arrays horizontally. This is the same operator you used to build matrices:

MATLAB
first = 'Grace';
last = 'Hopper';
full = [first ' ' last]            % 'Grace Hopper'
tag = strcat('id_', '42')          % 'id_42'

strcat on char arrays removes trailing whitespace from its arguments, which surprises many people; the bracket form keeps every space. To put text on separate lines use newline (MATLAB) or '\n' inside sprintf.

Numbers to text and back

Three functions do most conversions:

  • num2str(x) turns a number into text. num2str(pi) gives '3.1416', and num2str(pi, 8) gives '3.1415927'.
  • str2double(s) turns text into a number, and returns NaN when the text is not a number. It also accepts cells of text.
  • sprintf(format, ...) is the most flexible: it formats values using C-style placeholders and returns text instead of printing.

The common placeholders are %d (integer), %f (fixed decimals), %e (scientific), %g (shortest sensible), %s (text) and %% (a literal percent). A number between the percent sign and the letter sets the width and precision, so %8.3f means "eight characters wide, three decimals".

MATLAB
x = 3.14159;
msg = sprintf('x = %.2f, count = %d, name = %s', x, 7, 'run')
% msg = 'x = 3.14, count = 7, name = run'
sprintf('%d,', [1 2 3])     % '1,2,3,'   (format repeats for each value)
str2double('2.5e3')          % 2500
str2double('abc')            % NaN

Notice that the format is recycled when you pass an array, which is a neat way to build comma-separated lists. fprintf uses the same formats but prints to the screen (see variables, output and help).

Python Formatting like sprintf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The %g line shows why that format is popular: it picks fixed or scientific notation for you. The str2double helper mirrors MATLAB's habit of returning NaN instead of raising an error.

Searching and editing

A handful of functions cover everyday text work. All of them accept char arrays in both MATLAB and Octave:

MATLAB
s = 'the quick brown fox';
upper(s)                        % 'THE QUICK BROWN FOX'
strrep(s, 'quick', 'slow')      % 'the slow brown fox'
strtrim('   padded   ')         % 'padded'
strfind(s, 'o')                 % [13 18]
strcmp('abc', 'abc')            % 1
strcmpi('ABC', 'abc')           % 1  (ignores case)
strncmp('matrix', 'mat', 3)     % 1  (first 3 characters only)

strfind returns the starting positions of every match (1-based, like all MATLAB indexing). Never compare text with == on char arrays: it compares character by character and fails with an error if the lengths differ. Use strcmp.

Splitting and joining pieces

strsplit cuts text at a delimiter and returns a cell array of pieces, and strjoin reverses it:

MATLAB
parts = strsplit('red,green,blue', ',')
% parts = {'red', 'green', 'blue'}   (a 1x3 cell)
strjoin(parts, ' | ')                % 'red | green | blue'
numel(parts)                         % 3

The result is a cell because the pieces have different lengths and cannot share one char matrix. You read the second word with braces, parts{2}, as the next lesson explains.

Python Split, replace, join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python indexes from 0, so the stand-in adds 1 to show what strfind would return. The two o letters sit at positions 13 and 18 of the sentence.

Regular expressions

regexp finds patterns. Its first output is selected by the option you pass, which can be 'match' (the matching text), 'tokens' (the parenthesized groups), 'names' (named groups) or 'start' (positions). Add 'once' to get just the first hit instead of a cell of all hits:

MATLAB
log = 'error 404 at 10:32, error 500 at 11:05';
codes = regexp(log, '\d{3}', 'match')
% codes = {'404', '500'}
tok = regexp(log, '(\d+):(\d+)', 'tokens', 'once')
% tok = {'10', '32'}
clean = regexprep(log, '\d', '#')      % replaces every digit

The pattern language is Perl-compatible in both programs, so \d, +, and (...) behave as in most other languages. regexprep replaces matches and supports $1, $2 for captured groups.

Python Pattern matching with re

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows group references: the text 10:32 turns into 32h10. In MATLAB you would write '$2h$1' as the replacement.

Common pitfalls

  • Mixing quote styles. 'it''s' is how you put an apostrophe inside single quotes (double it). Inside double quotes you write "it's" directly.
  • Escape sequences. In a single-quoted char array, 'a\nb' is four literal characters. Only functions like sprintf and fprintf interpret \n. Octave's double-quoted text interprets them immediately.
  • Comparing with ==. Use strcmp or isequal, not ==, for char arrays.
  • Forgetting the type. disp(5) and disp('5') look alike but one is a number and one is a character with code 53. When something acts strangely, ask class(x).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the size of the char array 'hello'?

    A char array is a matrix with one character per column, so 'hello' is a single row of five characters.
  2. 2. Which function reliably compares two char arrays of different lengths?

    strcmp returns 0 or 1 whatever the lengths. The == operator compares element by element and raises a size error when the lengths differ.
  3. 3. What does str2double('abc') return?

    str2double returns NaN when the text is not a valid number, so you can test the result with isnan instead of catching an error.
  4. 4. Why does strsplit return a cell array?

    A char matrix needs every row to be equally long. A cell array can hold pieces of any length, one per cell.

Summary

  • Single-quoted text is a character array, a row vector of character codes; it works in MATLAB and Octave.
  • Double-quoted string objects exist only in MATLAB; in Octave double quotes make a char array that expands escapes.
  • Join with [a b] or strcat, compare with strcmp, and convert with num2str, str2double and sprintf.
  • strsplit and strjoin convert between text and cell arrays of pieces.
  • regexp and regexprep handle patterns; choose the output with 'match', 'tokens' or 'names'.

Next: Cell Arrays, where you'll store text and other mixed data in one container.