recipes : Text Processing : Concatenating strings and numbers

Problem

You want to concatenate (join) a string and a number.

Solution

Strings and numbers are different types of data and so cannot be mixed without first being converted to be the same type. There are two solutions. One is to use the num2str command which, as you'd expect, converts a number to a string.

X=7;
[num2str(7), ' brothers']
ans =

7 brothers

The other approach is to use the sprintf command, which allows for greater flexibility although its syntax may appear odd at first.

X=7;
sprintf('%d brothers',X)
ans =

7 brothers
Discussion

There is no particular "right" way to do this, so it's a matter of style and preference. However, if you have to perform a complex concatenation, with many numbers inserted at various points in a string, then the sprintf method will be easier. Furthermore, sprintf allows you to format numbers before displaying them as a string. For example, reducing the number of significant figures: sprintf('pi to 2 s.f. is %0.2f',pi)