MATLAB 中 disp 函数用于在命令窗口显示变量、表达式和字符串,语法为 disp(variable_or_expression)。它可显示变量或表达式,使用单引号括起来的字符串,多行输出、空行和通过 printf 函数格式化的输出。

MATLAB 中 disp 函数
disp 函数用于在 MATLAB 命令窗口中显示变量、表达式和字符串。它是最基本的输出函数,常用于调试、数据探索和输出结果。
语法:
disp(variable_or_expression)
参数:
-
variable_or_expression:要显示的变量、表达式或字符串。
用法:
- 显示变量或表达式:直接将变量名称或表达式作为参数传递给 disp 函数。
>> a = 5; >> disp(a) % 显示变量 a 的值 5
- 显示字符串:使用单引号 (') 将字符串括起来,然后将其作为参数传递。
>> disp('Hello, MATLAB!') % 显示字符串 "Hello, MATLAB!"
Hello, MATLAB!- 显示多行输出:如果要显示多行输出,可以使用逗号 (,) 将表达式或字符串分隔开来。
>> disp('Line 1', 'Line 2', 'Line 3')
Line 1
Line 2
Line 3特殊用法:
- 空行:要输出空行,只需将空字符串作为参数传递。
>> disp(' ')- 格式化输出:可以使用 printf 函数对输出进行更精细的格式化。
示例:
% 显示变量的值和类型
disp(['Variable a:', a, ' (class:', class(a), ')'])
% 显示多行字符串
disp(['First line' newline 'Second line'])
% 输出空行
disp(' ')
% 使用 printf 格式化输出
disp(sprintf('The area of a circle with radius %.2f is %.2f', 5, pi * 5^2))










