How to bold in a sprintf function?

107 ビュー (過去 30 日間)
Elena
Elena 2022 年 3 月 29 日
コメント済み: Jan 2022 年 3 月 29 日
For below, m and b are going to be numbers, how can i make only those parts of the statement bold? I know its \bf somewhere but i couldnt get it to work.
sprintf('Y = %.2f X + %.2f',m,b)
As a follow up, I also have this where im trying to make every 0 or multiple of 10 bold on the x-axis, how can i incoorporate that? This is what i have, once again could get \bf to work anywhere
endAt = length(myAx.XAxis.TickLabels)
for i=0:10:endAt
myAx.XAxis.TickLabels{0} = i;
end

採用された回答

Star Strider
Star Strider 2022 年 3 月 29 日
You can do that in a a text call (with any text objects, such as title, xlabel, etc.), nowhere else.
m = pi;
b = exp(1);
text(0.3, 0.7, sprintf('Y = \\bf%.2f\\rm X + \\bf%.2f\\rm',m,b))
.
  2 件のコメント
Elena
Elena 2022 年 3 月 29 日
ah thank you!!
Star Strider
Star Strider 2022 年 3 月 29 日
As always, my pleasure!

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

その他の回答 (2 件)

Voss
Voss 2022 年 3 月 29 日
m = 2;
b = 1;
% set up normal and bold strings, for comparison:
str_normal = sprintf('Y = %.2f X + %.2f',m,b)
str_normal = 'Y = 2.00 X + 1.00'
% use \\ to "escape" the \, i.e., allow a backslash to "pass-through" sprintf()
% without interpretation:
str_bold = sprintf('Y = {\\bf%.2f} X + {\\bf%.2f}',m,b)
str_bold = 'Y = {\bf2.00} X + {\bf1.00}'
% make some lines to put in a legend, using str_normal and str_bold as
% their names:
x = 0:30;
h_normal = plot(x,m*x+b);
hold on
h_bold = plot(x,m*x+b);
legend([h_normal h_bold],{str_normal str_bold});
% set up the XTickLabels:
xtick_label = cell(size(x));
for ii = 1:numel(x)
if mod(x(ii),10) == 0 % x(ii) is a multiple of 10 (0 is a multiple of 10 too)
xtick_label{ii} = sprintf('{\\bf%d}',x(ii));
else
xtick_label{ii} = sprintf('%d',x(ii));
end
end
set(gca(),'XTick',x,'XTickLabel',xtick_label)

Jan
Jan 2022 年 3 月 29 日
編集済み: Jan 2022 年 3 月 29 日
Ticks = linspace(0, 30, 7);
ax = axes('XLim', [0, 30], 'XTick', Ticks, ...
'TickLabelInterpreter', 'latex');
for k = 1:numel(Ticks)
if rem(Ticks(k), 10) == 0
ax.XAxis.TickLabels{k} = ['\bf' ax.XAxis.TickLabels{k}];
end
end
% Or without a loop:
m = (rem(Ticks, 10) == 0);
ax.XAxis.TickLabels(m) = strcat('\bf', ax.XAxis.TickLabels(m)):
  2 件のコメント
Elena
Elena 2022 年 3 月 29 日
thank you! i just realised i can only accept one answer but i really appreciate it
Jan
Jan 2022 年 3 月 29 日
@Elena: You are welcome.
Accepting one answer is fine. The main point of accepting is to indicate, that this question does not need further attention. I have more points than I can eat, so I'm glad, if I can help to solve the problems. :-)

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

カテゴリ

Help Center および File ExchangeGrid Lines, Tick Values, and Labels についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by