我正在尝试在matlab中显示它们的值的变量名称和num2str表示形式(I am trying to display variable names and num2str representations of their values in matlab)

我试图产生以下内容:使用disp和num2str命令,x和y的新值分别为-4和7。 我试图做这个disp('x和y的新值分别是num2str(x)和num2str(y)'),但它给出了num2str而不是相应的值。 我该怎么办?

I am trying to produce the following:The new values of x and y are -4 and 7, respectively, using the disp and num2str commands. I tried to do this disp('The new values of x and y are num2str(x) and num2str(y) respectively'), but it gave num2str instead of the appropriate values. What should I do?

最满意答案

像Colin提到的那样,一个选项是使用num2str将数字转换为字符串,手动连接所有字符串并将最终结果输入disp 。 不幸的是,它会变得非常尴尬和乏味,特别是当你有很多数字要打印时。

相反,您可以利用sprintf的强大功能,这在MATLAB中非常类似于C编程语言。 这会产生更短,更优雅的语句,例如:

disp(sprintf('The new values of x and y are %d and %d respectively', x, y))

您可以使用格式说明符控制变量的显示方式。 例如,如果x不一定是整数,则可以使用%.4f ,而不是%d 。

编辑:像Jonas指出的那样,你也可以使用fprintf(...)而不是disp(sprintf(...)) 。

Like Colin mentioned, one option would be converting the numbers to strings using num2str, concatenating all strings manually and feeding the final result into disp. Unfortunately, it can get very awkward and tedious, especially when you have a lot of numbers to print.

Instead, you can harness the power of sprintf, which is very similar in MATLAB to its C programming language counterpart. This produces shorter, more elegant statements, for instance:

disp(sprintf('The new values of x and y are %d and %d respectively', x, y))

You can control how variables are displayed using the format specifiers. For instance, if x is not necessarily an integer, you can use %.4f, for example, instead of %d.

EDIT: like Jonas pointed out, you can also use fprintf(...) instead of disp(sprintf(...)).

更多推荐