Skip to content

MATLAB - 文本格式化

有效的文本格式化对于显示结果、创建报告和构建用户界面至关重要。现代 MATLAB 为此提供了强大而灵活的工具,主要通过 string 数组和 compose 函数,同时也支持传统的 C 风格函数,如 sprintf 和 fprintf。

现代方法:字符串数组和 compose 函数

Section titled “现代方法:字符串数组和 compose 函数”

自 R2016b 版本以来,MATLAB 引入了 string 数据类型(使用双引号 ""),与传统的字符向量(使用单引号 '')相比,它提供了显著的优势。对于格式化,compose 函数是推荐的现代方法。

% 创建字符串变量
item = "apples";
count = 12;
price = 0.5;
% 使用 compose 创建格式化字符串
message = compose("We have %d %s at $%.2f each.", count, item, price)
message =
"We have 12 apples at $0.50 each."

compose 函数在处理数组时其强大之处便显而易见:

items = ["apples", "oranges"];
counts = [12, 5];
inventory = compose("- %d %s", counts, items)
inventory =
2×1 string array
"- 12 apples"
"- 5 oranges"

现代和传统格式化函数都使用格式说明符,这是一个以 % 开头并定义值如何转换为文本的字符串。其通用结构是:

%[identifier][flags][width][.precision][subtype]conversion

唯一强制的部分是 % 和 conversion 字符。

  • conversion:最重要的部分。指定表示法(例如,d 表示十进制整数,f 表示定点浮点数,s 表示字符串,e 表示指数)。
  • precision:小数点 (.) 后面的数字。对于浮点数,它是小数位数(例如,%.2f 表示 2 位小数)。对于字符串,它是最大字符数。
  • width:输出的最小字符数。如果值较短,则用空格填充(如果使用 0 标志,则用零填充)。
  • flags:可选字符,用于修改输出,例如 -(左对齐),+(始终显示符号)和 0(用前导零填充)。
SpecifierDescription
%s字符向量或字符串
%d有符号十进制整数
%f定点浮点数
%e指数记数法(例如,3.14e+00)
%gf 或 e 中更紧凑的表示
%%一个字面意义的百分号 (%)
val = pi;
% 默认格式
compose("Value: %f", val)
ans = "Value: 3.141593"
% 两位小数
compose("Value: %.2f", val)
ans = "Value: 3.14"
% 总宽度为 10,用空格填充
compose("Value: |%10.2f|", val)
ans = "Value: | 3.14|"
% 总宽度为 10,左对齐
compose("Value: |%-10.2f|", val)
ans = "Value: |3.14 |"
% 总宽度为 10,用前导零填充
compose("Value: |%010.2f|", val)
ans = "Value: |0000003.14|"

虽然新代码推荐使用 compose,但您会经常遇到旧函数。它们仍然得到完全支持并且非常有用。

sprintf:将数据格式化为字符向量

Section titled “sprintf:将数据格式化为字符向量”

sprintf 的工作方式与 compose 类似,但返回的是字符向量('...'),而不是字符串。

name = 'Alice';
age = 30;
msg_char_vector = sprintf('User %s is %d years old.', name, age)
msg_char_vector =
'User Alice is 30 years old.'

fprintf:格式化并将数据打印到屏幕或文件

Section titled “fprintf:格式化并将数据打印到屏幕或文件”

fprintf 应用格式并将结果直接打印到命令窗口或指定的文件 ID。它不返回包含字符串的变量。

% 打印到命令窗口
fprintf('Processing file %d of %d...\n', 5, 100)
Processing file 5 of 100...
% 打印到文件
fileID = fopen('log.txt','w');
fprintf(fileID, 'Log entry: System is stable.\n');
fclose(fileID);

num2str:简单的数字到字符串转换

Section titled “num2str:简单的数字到字符串转换”

对于不带复杂格式的数字到字符串的基本转换,num2str 是一个直接的选择。

val = 42.126;
% 简单转换
str1 = num2str(val)
str1 = '42.127'
% 带精度控制
str2 = num2str(val, 4)
str2 = '42.13'