TExcelTAD
Home › MATLAB / Octave › Characters & Strings

Characters & Strings

MATLAB has two ways to store text:

  • Character arrays (char), written with single quotes: 'hello'. A char array is simply a row vector of characters, so everything you know about vectors applies to it. They work in every MATLAB version and in Octave.
  • String arrays (string), written with double quotes: "hello". Added in MATLAB R2016b/R2017a, each element is a whole piece of text. Octave doesn't have the string class (it treats "..." as a char array with escape sequences), so this course uses char arrays for all runnable code.

Char arrays are vectors

matlab · try it yourself
word = 'MATLAB';
disp(class(word))
disp(size(word))
disp(word(1))
disp(word(end:-1:1))
disp(word([1 2 3 1]))
disp(length('Hello, world'))
char
   1   6
M
BALTAM
MATM
12

Indexing, end, length and reversing work exactly as with numeric vectors.

Joining text

Concatenate char arrays with square brackets (or strcat, or horzcat). Numbers must be converted to text first with num2str or sprintf:

matlab · try it yourself
first = 'Grace';
last = 'Hopper';
full = [first ' ' last];
disp(full)
born = 1906;
disp([full ' was born in ' num2str(born) '.'])
disp(sprintf('%s (%d)', full, born))
Grace Hopper
Grace Hopper was born in 1906.
Grace Hopper (1906)

Warning: ['Year: ' 2024] does not give "Year: 2024": the number is converted to the character with code 2024. Always use num2str or sprintf for numbers.

Quotes inside text

To put a single quote inside a single-quoted char array, write it twice:

matlab · try it yourself
msg = 'It''s a beautiful day';
disp(msg)
disp(length(msg))
It's a beautiful day
20

Characters are numbers

Each character is stored as a numeric code (Unicode/ASCII). double reveals the codes, char converts back, and arithmetic on chars gives numbers:

matlab · try it yourself
disp(double('Az'))
disp(char(72))
disp('a' + 1)
disp(char('a' + 1))
shifted = char('HAL' + 1);
disp(shifted)
disp(upper('mixed Case'))
disp(lower('MIXED Case'))
    65   122
H
98
b
IBM
MIXED CASE
mixed case

Adding 1 to each letter of 'HAL' gives 'IBM', a famous film trivia joke. The arithmetic returns numbers; wrapping it in char turns them back into text.

Comparing text

== compares character by character and requires the same length. To compare whole texts, use the strcmp family:

Function Compares
strcmp(a, b) Exact equality
strcmpi(a, b) Equality ignoring case
strncmp(a, b, n) First n characters
strncmpi(a, b, n) First n characters, ignoring case
matlab · try it yourself
disp('cat' == 'cut')
disp(strcmp('cat', 'cat'))
disp(strcmp('cat', 'cats'))
disp(strcmpi('Cat', 'CAT'))
disp(strncmp('config.txt', 'config.ini', 6))
  1  0  1
1
0
1
1

Testing characters

isletter, isspace and isstrprop return a logical array with one value per character, so you can count or filter characters with logical indexing:

matlab · try it yourself
s = 'Room 42B, floor 3';
disp(sum(isletter(s)))
disp(s(isstrprop(s, 'digit')))
disp(sum(isspace(s)))
noSpaces = s(~isspace(s));
disp(noSpaces)
10
423
3
Room42B,floor3

Several lines of text

A char matrix holds several rows of text, but every row must have the same length, which is awkward. char pads shorter rows with spaces:

matlab · try it yourself
names = char('Ann', 'Bartholomew', 'Cy');
disp(size(names))
disp(names)
disp(['[' names(1, :) ']'])
    3   11
Ann        
Bartholomew
Cy         
[Ann        ]

In practice, a cell array of char arrays ({'Ann', 'Bartholomew', 'Cy'}) is the better way to store a list of texts of different lengths. Cell arrays get their own lesson.

MATLAB string arrays (MATLAB only)

For reference, this is how the same ideas look with MATLAB's string type. It doesn't run in Octave:

matlab
% MATLAB R2017a or later only
s = "Grace" + " " + "Hopper";       % + joins strings
n = strlength(s);                   % 12
words = ["red" "green" "blue"];     % a 1x3 string array
upper(words(2))                     % "GREEN"
contains(s, "Hop")                  % true

String arrays are convenient in modern MATLAB, but char arrays and cell arrays of char arrays remain fully supported and portable.

Test yourself

What is length('It''s')?

  1. 4
  2. 5
  3. 6
  4. An error

What does ['Total: ' num2str(15)] produce?

  1. Total: 15
  2. An error
  3. Total: followed by character code 15
  4. Total:15 without space

Which call compares two texts ignoring upper/lower case?

  1. strcmp
  2. strcmpi
  3. ==
  4. isequal