Clear Filters
Clear Filters

why do strings I define to same length have different lengths?

6 views (last 30 days)
I am defining entries for a legend on a plot figure. Here's my code:
lg1 = sprintf('Widebeam MP Mean = %7.4g Var = %7.4g',mn1, vr1);
lg2 = sprintf('CPM 0 Mean = %7.4g Var = %7.4g',mn2, vr2);
lg3 = sprintf('Standard MP Mean = %7.4g Var = %7.4g',mn3, vr3);
lg4 = sprintf('Coarse Widebeam MP Mean = %7.4g Var = %7.4g',mn4, vr4);
When I examine the length of these strings, they are not always identical. But, more important to - for esoteric presentation [of results] reasons is that when I use legend() to display the array [lg1; lg2; lg3 lg4] the lines have different apparent lengths (more than the variance in length() lengths) and they don't line up vertically. lg2 is always the shortest - it has the most blank spaces. lg4 is always the longest. The numeric values of the mean are 0-3 digits; the values for variance can be 0-4 digits. BUT, these don't seem to be the issue (mean & variance length in digits). Rather, it's the size in pixels of the letters in the legend names.
Ultimately, I want the words 'Mean" and "Var" to align vertically. How can I force this to happen?

Accepted Answer

Stephen23
Stephen23 on 9 May 2018
Edited: Stephen23 on 9 May 2018
This happens because the font that you are using to display those strings is not a fixed-width font (i.e. is not monospaced), and the characters (including spaces) all have different widths. Read about different type-faces here, and what the difference between fixed-width (monospaced) and proportional type faces:
In general if you want specific parts of the strings to always align in columns then basically you need to do either one of these:
  1. use a monospace font
  2. display the data in some kind of table (e.g. in a GUI, or using a markup language, e.g. LaTex or HTML and some appropriate viewer).
Note that for legend you can use the option 'FontName' to select your favorite monospaced font, or use the handy value 'FixedWidth', which will use some system default monospaced font:
legend(...,'FontName','FixedWidth')
  5 Comments
Stephen23
Stephen23 on 9 May 2018
"I am running ver. 2015b. Is it possible these features were added more recently?"
You can check this yourself by looking at the help of your installed MATLAB (this is always the ultimate reference that you should use): go to the legend page, click on the Legend Properties link, then scroll down to the Font parameter FontName.
I don't see any reason why it should not work, but I will have to try it myself.
Dean Ranmar
Dean Ranmar on 9 May 2018
thanks. I did do that first - my documentation doesn't list 'FixedWidth' AND, it describes a different method for controlling the FontName. I will study it and make adjustments.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!