Making strings from mixed types
Problem
You want to make a string that contains number values from variables.
Solution
Strings are simply vectors containing numbers of type char, and a char is an 8-bit number. For example, in the case below, the number 68 represents the letter 'D'.
x = 68; [ 'The value of x is ' x] % returns 'The value of x is D'
One solution is to use num2str() to convert the number to a string. In the case below, 68 gets converted to the characters '6' and '8', which are represented by the numbers 54 and 56
x = 68; [ 'The value of x is ' num2str(x)] % returns The value of x is 68 int32(num2str(x)) % returns [ 54 56 ]
A better solution is to use the sprintf() function, which is more flexible and has a cleaner syntax.
x = 68; sprintf('The value of x is %d', x) % returns 'The value of x is 68'
sprintf() can print more than one number, and it can insert strings. It can also be used to pad numbers so that they take up a fixed number of columns (useful for printing aligned columns of numbers), and to specify the precision of floating point numbers.
sprintf('The square root of %d is %f. %s', x, sqrt(x), 'extra string') % returns 'The square root of 68 is 8.246211. extra string' sprintf('The square root of %4d is %.3f', x, sqrt(x)) % returns 'The square root of 68 is 8.246'