MATLAB sprintf Function and title Function
Sep. 12, 2022 • Updated Nov. 18, 2023
今天在学MATLAB的GMM示例时 1,看到了一个添加图像标题比较漂亮的实现方法,使用了sprintf 2向title 3添加参数:
1
2
3
4
5
6
7
8
9
10
11
12
clc, clear, close all
mu = 0;
sigma = 1;
x = -5:0.01:5;
y = normpdf(x, mu, sigma);
figure(1)
plot(x, y, LineWidth=1.5);
title(sprintf('Normal Distribution PDf\n mu = %d, sigma = %d', mu, sigma))
box on
grid on

但是,sprintf函数的目的是为了向命令行中打印文本,所以它不支持LaTeX解释器,这一点使得这种用法其实不是很实用。
Added on Nov. 18, 2023. Actually, sprintf function could be used while adopting text interpreter, by formatting control sequence as well. The more information could be found in Blogs 4 and 5.
但是,受此启发,可以使用sprintf函数向eval函数传递参数,可以提高代码的可读性。
顺便学习了一下title函数的用法,title函数是可以支持双行标题和子标题的。
双行标题用法:
1
2
3
4
5
6
7
figure(2)
plot(x, y, LineWidth=1.5);
t = ['Normal Distribution PDF';
'$\mu$ = ', num2str(mu), ', $\sigma$ = ', num2str(sigma)];
title(t, Interpreter="latex")
box on
grid on

子标题用法:
1
2
3
4
5
6
7
figure(3)
plot(x, y, LineWidth=1.5);
t = 'Normal Distribution PDF';
subt = ['$\mu$ = ', num2str(mu), ', $\sigma$ = ', num2str(sigma)];
[tt, ss] = title(t, subt, Interpreter="latex");
box on
grid on

其中,变量tt和ss是标题和子标题所对应的Text对象,可以分别修改它们的行为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
tt =
Text (Normal Distribution PDF) with properties:
String: 'Normal Distribution PDF'
FontSize: 11
FontWeight: 'bold'
FontName: 'Helvetica'
Color: [0 0 0]
HorizontalAlignment: 'center'
Position: [6.3798e-06 0.4257 0]
Units: 'data'
Show all properties
BackgroundColor: 'none'
BeingDeleted: off
BusyAction: 'queue'
ButtonDownFcn: ''
Children: [0×0 GraphicsPlaceholder]
Clipping: off
Color: [0 0 0]
ContextMenu: [0×0 GraphicsPlaceholder]
CreateFcn: ''
DeleteFcn: ''
EdgeColor: 'none'
Editing: off
Extent: [-1.9169 0.4257 3.8338 0.0212]
FontAngle: 'normal'
FontName: 'Helvetica'
FontSize: 11
FontSmoothing: on
FontUnits: 'points'
FontWeight: 'bold'
HandleVisibility: 'off'
HitTest: on
HorizontalAlignment: 'center'
Interactions: [1×1 matlab.graphics.interaction.interactions.EditInteraction]
Interpreter: 'latex'
Interruptible: on
LineStyle: '-'
LineWidth: 0.5000
Margin: 3
Parent: [1×1 Axes]
PickableParts: 'visible'
Position: [6.3798e-06 0.4257 0]
Rotation: 0
Selected: off
SelectionHighlight: on
String: 'Normal Distribution PDF'
Tag: ''
Type: 'text'
Units: 'data'
UserData: []
VerticalAlignment: 'bottom'
Visible: on
References