zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Matlab中disp函数的使用

MATLAB 函数 使用
2023-09-11 14:14:48 时间

目录

显示变量值

显示矩阵及其列标签

在命令行窗口中显示超链接

在同一行上显示多个变量


        disp函数的作用是显示变量的值。即:

disp(x)

        disp(X) 显示变量 X 的值,而不打印变量名称。显示变量的另一种方法是键入它的名称,这种方法会在值前面显示一个前导“X =”。如果变量包含空数组,则会返回 disp,但不显示任何内容。

显示变量值

        创建一个数字变量和一个文本变量。

A = [15 150];
S = 'Hello World.';

显示每个变量的值。

disp(A)

    15   150


disp(S)

Hello World.

显示矩阵及其列标签

        显示矩阵,并列为提供标签Corn、Oats和Hay。

X = rand(5,3);
disp('     Corn      Oats      Hay')

     Corn      Oats      Hay


disp(X)

    0.8147    0.0975    0.1576
    0.9058    0.2785    0.9706
    0.1270    0.5469    0.9572
    0.9134    0.9575    0.4854
    0.6324    0.9649    0.8003

在命令行窗口中显示超链接

        通过包含 HTML 超链接代码作为 disp 的输入来显示网页链接。例如,显示指向 MathWorks® 网站的链接。

X = '<a href = "https://www.mathworks.com">MathWorks Web Site</a>';
disp(X)


MathWorks Web Site

在同一行上显示多个变量

        以下介绍了可以在命令行窗口的同一行中显示多个变量值的三种方法。使用 [] 运算符将多个字符向量串联在一起。使用num2str函数将任何数值转换为字符。使用disp显示结果。

name = 'Alice';   
age = 12;
X = [name,' will be ',num2str(age),' this year.'];
disp(X)


Alice will be 12 this year.

        使用sprintf创建文本,然后通过disp显示它。

name = 'Alice';   
age = 12;
X = sprintf('%s will be %d this year.',name,age);
disp(X)


Alice will be 12 this year.

        使用 fprintf 直接显示文本,无需创建变量。不过,要确保正常终止显示,必须在文本末尾处添加换行 (\n) 元字符。

name = 'Alice';   
age = 12;
fprintf('%s will be %d this year.\n',name,age);


Alice will be 12 this year.