How to preserve subscript or superscript formatting in a text string?
24 次查看(过去 30 天)
显示 更早的评论
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 个评论
Ricardo Campos
2024-5-15
编辑:Ricardo Campos
2024-5-15
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 :)
回答(1 个)
George Abrahams
2024-5-15
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!