I am trying to display variable names and num2str representations of their values in matlab

disp, matlab, string

Solution

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(...))`.

Problem

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?

Original source