4

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?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
cuabanana
  • 126
  • 1
  • 1
  • 7

2 Answers2

5

Try:

disp(['The new values of x and y are ', num2str(x), ' and ', num2str(y), ', respectively']);

You can actually omit the commas too, but IMHO they make the code more readable.

By the way, what I've done here is concatenated 5 strings together to form one string, and then fed that single string into the disp function. Notice that I essentially concatenated the string using the same syntax as you might use with numerical matrices, ie [x, y, z]. The reason I can do this is that matlab stores character strings internally AS numeric row vectors, with each character denoting an element. Thus the above operation is essentially concatenating 5 numeric row vectors horizontally!

One further point: Your code failed because matlab treated your num2str(x) as a string and not as a function. After all, you might legitimately want to print "num2str(x)", rather than evaluate this using a function call. In my code, the first, third and fifth strings are defined as strings, while the second and fourth are functions which evaluate to strings.

Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89
5

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

Eitan T
  • 32,660
  • 14
  • 72
  • 109