How to preserve subscript or superscript formatting in a text string?
24 views (last 30 days)
Show older comments
I'm reading out some text strings (units) from some Excel files:
filename = 'AAA.xlsx';
opt = detectImportOptions(filename);
opt.VariableUnitsRange = '2:2'; % 2nd row
T1 = readtable(filename, opt);
The problem is that I would have a unit like this: mol kg^-1, and after it is read out, the superscript formatting of "-1" is lost.
Is there an option so that I could preserve the superscript formatting?
Thanks.
1 Comment
Ricardo Campos
on 15 May 2024
Edited: Ricardo Campos
on 15 May 2024
Hi
It might come a little late, but I had the same problem while working on a project. For all I could find, MATLAB does not support subscript nor superscript directly. However I was able to find some solutions (this in MATLAB2024a):
i. Unicode Characters: Unicode has subscript and superscript characters encoded. Using a table, or ChatGPT, you can get them and MATLAB has some suport (although limited) for them. Use this link for example: https://www.codetable.net/unicodecharacters?page=28. You can also ask ChatGPT. Here is an example:
fprintf('x%c + y%c = z%c\n', char(178), char(8322), char(179));
In my command window, the subscript was a little less perceptible, but i don't find it much of a problem.
ii. HTML: This is the solution I ended up implementing, since I wanted to display information in a figure. Here is a simplified version of how i did it:
% Define variables (from an Exel file in your case)
A='n+1';
B='n';
C='2';
% Create basic text. '%s' allows for sprintf to change the string later
html_text="<p>Equation:<br> z<sub>%s</sub> = z<sub>%s</sub> + y<sup>%s</sup></p>";
% Replace '%s' for variable values
html_text1=sprintf(html_text,A,B,C);
% Create basic figure
Fig=uifigure('Color','w','Position',[200 100 500 500]);
h = uihtml(Fig,Position=[50 0 500 500]);
% Setting the HTML source to the string
h.HTMLSource=html_text1;
As you can imagine, the HTML approach allows for better formatting, going much further than just subscripts and superscripts (given that you know HTML), but it requires you to create a figure to display the info.
I hope I was of help.
Good Luck, and Happy coding :)
Answers (1)
George Abrahams
on 15 May 2024
For text-based graphics objects, such as title or xlabel, MATLAB uses the following syntax for superscripts and subscripts:
title('^{superscript} normal _{subscript}')
For more complex text formats, e.g., including greek letters, mathematical symbols, and fractions, the LaTeX interpreter can be used. The above would instead become:
title('$^{superscript} normal _{subscript}$', 'Interpreter', 'latex')
This syntax will not, however, be displayed in the Variables Editor, Command Window, etc. - only in figures.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!