Displaying exponential notation with num2str?

22 ビュー (過去 30 日間)
Michael
Michael 2022 年 8 月 24 日
回答済み: Steven Lord 2022 年 8 月 24 日
I have a value that I want to display within a textbox in a figure. The value hoewer needs to be in exponential notation.
Example:
lambda = 2.4321;
vD = 3.2e5;
fighandle = figure(1);
fighandle.Color = [1,1,1];
fighandle.Position = [10,50,600,400];
fighandle.Name = 'Test';
xlabel('t [min]','FontSize',12,'Interpreter','latex');
ylabel('Temperatur [$^\circ$C]','FontSize',12,'Interpreter','latex');
annotation('textbox', [0.66, 0.15, 0.1, 0.1], ...
'String', {['$\lambda$ = ' num2str(round(lambda,3),'%.3f') ' W/mK'], ...
['$v_D$ = ' num2str(round(vD,1),'%.1f') ' m/s']}, ...
'BackgroundColor', 'White', ...
'Interpreter','latex');
The result looks like this:
But i want the variable b to look like this:
Any ideas? Thank you very much for the help!

採用された回答

Star Strider
Star Strider 2022 年 8 月 24 日
I wrote a little utility program to do that sort of thing a few years ago.
Try this —
Q1 = [-pi*1000; 0; pi*100];
expstr = @(x) [x(:).*10.^ceil(-log10(abs(x(:)+(x==0)))) floor(log10(abs(x(:)+(x==0))))]; % Updated: 2021 05 04
Result = sprintf('%+.4fe%+04d\n', expstr(Q1).')
Result =
'-3.1416e+003 +0.0000e+000 +3.1416e+002 '
V = expstr(Q1)
V = 3×2
-3.1416 3.0000 0 0 3.1416 2.0000
Create the sprintf format string (that I use here) to give the result you want.
.
  2 件のコメント
Michael
Michael 2022 年 8 月 24 日
編集済み: Michael 2022 年 8 月 24 日
Thank you very much! That did, what I was looking for :)
I implemented it this way within the annotation textbox:
vD_expstr = expstr(vD);
% ...
['$v_D$ = ' num2str(round(vD_expstr(1),1),'%.1f') ' $\cdot$ 10' num2str(vD_expstr(2),'$^{%.0f}$') ' m/s']
Star Strider
Star Strider 2022 年 8 月 24 日
As always, my pleasure!
That will work, since num2str allows format strings, although sprintf might be an easier way to implement it.
I created ‘expstr’ precisely for the purpose you’re using it!

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 8 月 24 日
Another function that might be of interest to you is formattedDisplayText, if you want to capture how the variable would be displayed in MATLAB using a certain display format.
x = pi
x = 3.1416
y1 = formattedDisplayText(x)
y1 =
" 3.1416 "
format longeng
x
x =
3.14159265358979e+000
y2 = formattedDisplayText(x)
y2 =
" 3.14159265358979e+000 "

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by