recipes : Plotting : Plot Manipulation : Ensuring underscores don't lead to subscripted characters

Problem

Why do my figure titles (or other text in a figure) sometimes have subscripted characters in them?

Solution

Matlab allows a variety of different font modifications to be used in figures. Subscripts are created by the presence of an underscore before a regular text character. Your options are to either replace the underscore with a different character (such as a space) or to "escape" the underscore with a forward slash. Here's how to do the latter:

%Let's make a figure with an underscope in the title. 
plot([0,1],[0,1])
txt='This is a title with a _symbol';
title(strrep(txt,'_','\_'))
Discussion

The forward slash is a common way of escaping special characters such as the underscore. If you dabble in regular expressions you will see the same principle in action. The sprintf command uses % symbols as a special character to denote locations where text is inserted into a string. In this case, to escape the % character two % in series are used instead of a forward slash. e.g. sprintf('%d%% of hard disks fail in the end',100)