# Example of Inserting Mathematical Formulas into MATLAB Graphics

The following code:

xlabel('Resistance (m\Omega)') ylabel('Capacitance (\muF)') text(0.1,0.9,'1+e^{i\pi}=0') text(0.1,0.8,'X_{y_z}=\infty') text(0.1,0.7,'X^{y^z} \geq 0') text(0.1,0.6,'X\_y has no subscripted y')

produced the following figure:

For further reference, see Mathworks' full specifications on all the valid symbols for text labels.

What if you wanted to customize labels on your graph according to variable values? For example, a graph showing harmonic motion with explicit listing of the motion's frequency and phase.

Start with setting up the data and a simple graph:

t=linspace(0,1,100); ph=0; f=1; w=2*pi*f; x=sin(w*t+ph); plot(t,x) xlabel('Time (s)'); ylabel('Displacement (mm)');

Now, to add annotations including variable values, we have two options: either build up the annotation string piece by piece, or use a formatted print statement to create it all at once.

Option 1 (piecewise string construction):

mytext=['\phi = ' num2str(ph)]) text(0.1,0,mytext)

This method has the option of being simple for simple text, but gets tedious for longer strings. Every numeric variable we include has to be surrounded by a `num2str()`

function, and this can make for very long command lines.

Option 2 (formatted print statement):

mytitle=sprintf('Harmonic motion for \\omega=%.2f rad/s (f=%.2f Hz)',w,f); title(mytitle)

This method is a bit more compact, and provides extra flexibility on the formatting of any given numeric variable. Similar to C or Fortran formats, we can specify the total amount of space reserved for a particular variable, the number of decimals, etc.

One other thing to note here is that with a formatted print statement, we need to double up the number of `\`

characters if we want to use Greek or other symbolic characters. The `sprintf()`

function uses the `\`

character to indicate a control character, and a `\\`

sequence is interpreted as a literal `\`

and passed on.

Final results for this are shown below:

See the reference documentation for sprintf at Mathworks' site for more information.